首页 > 解决方案 > 计算 Spring Job 执行时间

问题描述

我有这个非常基本的 Spring Job 示例。

@Scheduled(fixedRate = 90000)
    public void myScheduler() throws Exception {

        // Print here execution time into console and save into DB
    }

我必须做一些非常繁重的计算。有没有办法计算总执行时间?有一个带有监听器的解决方案,但我想在作业中执行它,因为我想在作业实现代码中执行它。

标签: javaspringspring-boot

解决方案


可以很好地使用@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无法获取稍后保存的任何参数。


推荐阅读