Can be nicely done using @Aspect
First, add to your pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Second, make sure that your class has @Component
and @EnableScheduling
.
Finally, create an Aspect class for Spring's Scheduled annotation
@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)
}
}
}
Notice that in this way the executionTime time needs to be persisted from the Aspect class, as a method with @Scheduled
can not get any arguments to be later saved.