Java 计算Spring作业执行时间
我有一个非常基本的Spring Job示例Java 计算Spring作业执行时间,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个非常基本的Spring Job示例 @Scheduled(fixedRate = 90000) public void myScheduler() throws Exception { // Print here execution time into console and save into DB } 我得做一些非常繁重的计算。有没有办法计算总执行时间?listener有一个解决方案,但我希望在作业内部执行,因为我希望在作业实现代码中执行该解决方案
@Scheduled(fixedRate = 90000)
public void myScheduler() throws Exception {
// Print here execution time into console and save into DB
}
我得做一些非常繁重的计算。有没有办法计算总执行时间?listener有一个解决方案,但我希望在作业内部执行,因为我希望在作业实现代码中执行该解决方案。如果您的项目/应用程序很轻,您可以只放置一些:
long startTime=System.getCurrentTimeInMillis();
//不管这里的处理时间有多长
long-endTime=System.getCurrentTimeInMillis();
长处理时间=结束时间-开始时间;
//打印
//是否存储到数据库
但是,如果您的项目/应用程序很大(即有很多调度器),那么您可能需要向它们注入前/后方面(也称为切入点)
请参阅。可以使用
@Aspect
首先,将以下内容添加到您的pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
请注意,通过这种方式,executionTime需要从Aspect类中持久化,因为带有
@Scheduled
的方法无法获取任何要在以后保存的参数。您可以使用Spring Framework来计算执行时间。对于多个任务,您也可以使用秒表
秒表秒表=新秒表(“秒表演示”);
StopWatchDemo StopWatchDemo=新的StopWatchDemo();
秒表启动(“秒表任务1”);
stopWatchDemo.performTask1();
秒表;
秒表启动(“秒表任务2”);
stopWatchDemo.performTask2();
秒表;
获取所有任务(此处为task1和task2)的总执行时间
System.out.println(“秒表演示任务总计:“+stopWatch.getTotalTimeSeconds()+”秒”);
获取任务执行时间
for(TaskInfo TaskInfo:stopWatch.getTaskInfo()){
System.out.println(taskInfo.getTaskName()+“-”+taskInfo.getTimeSeconds()+“secs”);
}
Instant begin=Instant.now();
//做任何事。。。
瞬间结束=瞬间。现在();
长增量=持续时间.between(begin,end).toMillis();
即时类需要Java8@MS90,我不打算开始一场教科书辩论。你在某些方面是对的(双关语)。然而,对于这个答案,我想它们可以互换使用。放松点,你说得对。切入点确实是(方面之前/之后)。只是一场文字游戏@EdwardAungIs还有更好的选择吗?检查。你是在测量挂钟时间还是cpu时间?可能是重复的谢谢,但有没有办法使用此代码了解我的方法,因为我需要将结果打印到相同的方法中?什么意思将结果打印到相同的方法中?你的意思是进入日志?可以编辑代码并打印方面类中的方法和类名。
@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)
}
}
}