计算Spring Job的执行时间

Pet*_*zov 9 java spring spring-boot

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

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

        // Print here execution time into console and save into DB
    }
Run Code Online (Sandbox Code Playgroud)

我必须做一些非常繁重的计算。有没有一种方法可以计算总执行时间?侦听器有一个解决方案,但是我想在作业内部执行此操作,因为我想在Job实施代码中执行此操作。

Ste*_*ler 6

可以很好地使用 @Aspect

首先,添加到您的pom.xml

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

其次,确保您的班级有@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)
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

请注意,以这种方式需要从Aspect类中@Scheduled保留executeTime时间,因为不能获取任何参数以稍后保存。


Edw*_*ung 4

如果你的项目/应用程序很轻,你可以只放一些:

long startTime = System.getCurrentTimeInMillis();
// whatever long processing here
long endTime = System.getCurrentTimeInMillis();
long processingTime = endTime - startTime;
// do print 
// do store to DB
Run Code Online (Sandbox Code Playgroud)

但是,如果您的项目/应用程序很大(即有很多调度程序),您可能需要向它们注入之前/之后方面(也称为切入点)。

请参阅此 Stackoverflow 答案