Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using @Scheduled and @Async together?

If i want a method to repeat async, can i use @Scheduled and @Async together ?

@Async
@Scheduled(fixedDelay = x)
public void doSomethingEveryXMinuteAsync() { 
  // action 
}

or is there another standard way to achive this ?

like image 463
Anders Pedersen Avatar asked Feb 27 '17 10:02

Anders Pedersen


2 Answers

There is no need to use @Async. Just use fixedRate attribute of @Scheduled instead of fixedDelay. Spring will make another invocation on the method after the given time regardless of any call is already being processed.

UPDATE:

Apparently fixedRate attribute does not enforce a scheduled method to be called asynchronously and increasing pool size of scheduler task executor only enables asynchronous execution of independent @Scheduled methods. Even putting @Async on the method does not make it work as OP has asked.

ScheduledAnnotationBeanPostProcessor just creates a Runnable from the @Scheduled method and does not create any pointcut as @Async method processor would. ScheduledThreadPoolExecutor waits until Runnable#run() is finished and sets the next execution time using the start time and the fixed rate. So if the method call takes more time than the scheduled time, the next task is triggered right after the previous call is finished.

An easy solution would be extracting the actual method into another class as a @Async method and calling this method from the @Scheduled method.

like image 145
Yuqu Avatar answered Sep 18 '22 12:09

Yuqu


Implement SchedulingConfigurer and override configureTasks method. Define poolsize more than one, It will work as you are expecting.

like image 39
Sarang Avatar answered Sep 18 '22 12:09

Sarang