using @Scheduled and @Async together?

你说的曾经没有我的故事 提交于 2020-08-02 09:39:54

问题


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 ?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/42482865/using-scheduled-and-async-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!