定时任务一直用的spring的@Scheduled注解,有天突然发现所有的定时任务突然全部不执行了。查看日志看到其中一个定时任务一直在一个循环里运行没结束。通过这里可以发现@Scheduled启动过程是一个单线程同步启动过程,故一旦中途被阻塞,会导致整个启动过程阻塞,其余的定时任务都不会启动。
网上的教程是添加异步注解@Async
@Component
@EnableScheduling
public class AsyncTaskHandlerTask {
@Scheduled(fixedDelay = 1000)
@Async
public void task1() {
while(true){
....
}
}
@Scheduled(fixedDelay = 1000)
@Async
public void task2() {
while(true){
....
}
}
}
加上注解貌似可以了,运行几天都正常。
几天后,又阻塞了…
经过一通分析过后,发现就是加了@Async的锅。定时每次一提交,由于是异步的,就会马上标记已执行完(实际还没执行完),之后第二次定时任务,第三次…直到把线程池耗尽。
解决办法
看了一下@EnableScheduling注解源码,注释上非常详细,甚至例子都给出来了
When more control is desired, a @Configuration class may implement
SchedulingConfigurer. This allows access to the underlying
ScheduledTaskRegistrar instance. For example, the following example
demonstrates how to customize the Executor used to execute scheduled
tasks:
实际上已经说的很明白了,更多的控制,只需要继承 SchedulingConfigurer 这个类
下面是注释给的例子:
@Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
@Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(100);
}
}
之后再执行不仅以多线程来启动定时任务,而且也不会出现定时任务重复并发执行的问题
最后再说一句,并不是说@Async就不可取,得看你实际上定时任务的执行时间,如果能保证每次定时任务在你规定的时间间隔内执行完,那下次定时任务来也不会出现阻塞问题。归根结底还是线程资源不够用的问题。