我正在尝试使用java spring中的@Scheduled注释以固定速率执行任务.但是,如果任务比速率慢,那么默认情况下spring似乎不会以固定速率执行fixedRate任务.是否有一些设置我可以添加到我的弹簧配置来改变这种行为?
例如:
@Service
public class MyTask{
@Scheduled(fixedRate = 1000)
public void doIt(){
// this sometimes takes >1000ms, in which case the next execution is late
...
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个解决方案,但似乎不太理想.基本上,我只是用线程池替换默认的单线程执行器,然后我有一个调度方法调用异步方法,因为@Async注释允许并发执行:
@Service
public class MyTask{
@Async
public void doIt(){
// this sometimes takes >1000ms, but the next execution is on time
...
}
}
@Service
public class MyTaskScheduler{
...
@Scheduled(fixedRate = 1000)
public void doIt(){
myTask.doIt();
}
}
@Configuration
@EnableScheduling
@EnableAsync
public class MySpringJavaConfig{
@Bean(destroyMethod = "shutdown")
public …Run Code Online (Sandbox Code Playgroud)