java - 计算 Spring Job 执行时间
问题描述
我有这个非常基本的 Spring Job 示例。
@Scheduled(fixedRate = 90000)
public void myScheduler() throws Exception {
// Print here execution time into console and save into DB
}
我必须做一些非常繁重的计算。有没有办法计算总执行时间?有一个带有监听器的解决方案,但我想在作业中执行它,因为我想在作业实现代码中执行它。
解决方案
可以很好地使用@Aspect
首先,添加到您的pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
其次,确保你的班级有@Component
和@EnableScheduling
。
最后,为 Spring 的 Scheduled 注解创建一个 Aspect 类
@Aspect
@Component
public class TimeScheduler {
@Around("@annotation(org.springframework.scheduling.annotation.Scheduled)")
public void timeScheduledMethod(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("starting stopwatch");
Object result = null;
StopWatch watch = new StopWatch();
try {
watch.start();
result = joinPoint.proceed();
} finally {
watch.stop();
long executionTime = watch.getLastTaskTimeMillis();
String className = joinPoint.getTarget().getClass().getSimpleName();
String methodName = joinPoint.getSignature().getName();
// print to log/console all the details you need: Time took,
// method name, class name etc...
System.out.println("Time took: [" + executionTime + "] ms");
System.out.println("Class: " + className);
System.out.println("Method: " + methodName);
// db.save(executionTime)
}
}
}
请注意,通过这种方式,executionTime 时间需要从 Aspect 类中持久化,因为该方法@Scheduled
无法获取稍后保存的任何参数。
推荐阅读
- asp.net-mvc - 从 Kentico 自定义表中填充我的 MVC 视图中的下拉列表
- r - gam 包上的命名空间说明符不起作用
- c# - ?? 或 .GetValueOrDefault()
- haskell - 以与 Free Monad 兼容的方式定义 Free Bind
- string - 在 C++ 中将剪贴板文本转换为类似中文的字符
- python - 如何使用python更改.mat文件中的数组名称
- ruby-on-rails - 如何在rails中将参数传递给with_api_auth(access_id,secret_key)
- php-5.5 - 不应通过浏览器检查在 POST 方法上修改表单数据
- php - 当我将输入输入到数据库中的阿拉伯语存储中时,例如''??? ?? ? ????” 我如何用 sqlserver 修复它
- html - html table -- 设置列以占用剩余空间,并且至少 300px 宽度