一起使用@Scheduled和@Async? [英] using @Scheduled and @Async together?

查看:499
本文介绍了一起使用@Scheduled和@Async?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我希望重复异步的方法,我可以同时使用@Scheduled和@Async吗?

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 ?

推荐答案

无需使用@Async.只需使用 fixedRate 属性,而不是fixedDelay.在给定的时间之后,Spring将再次对该方法进行调用,而不管任何调用已在处理中.

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.

更新:

显然,fixedRate属性不会强制调度的方法被异步调用,并且增加调度程序任务执行器的池大小只能启用独立的@Scheduled方法的异步执行.甚至将@Async放在方法上也无法使其按照OP的要求工作.

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只能从@Scheduled方法创建一个Runnable,并且不会像@Async方法处理器那样创建任何切入点.ScheduledThreadPoolExecutor 等到Runnable#run()完成,然后使用开始时间和固定速率设置下一个执行时间.因此,如果方法调用花费的时间比计划的时间长,则在上一个调用完成后立即触发下一个任务.

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.

一个简单的解决方案是将实际方法作为@Async方法提取到另一个类中,然后从@Scheduled方法调用此方法.

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

这篇关于一起使用@Scheduled和@Async?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆