解决定时器同一时刻执行多条任务时阻塞问题
普通的定时任务,会一个一个执行,当同一时间有多个定时任务启动并且含有数据量比较大的任务时,会阻塞其他的定时任务,这样会产生一系列的问题;
解决办法:将定时任务放入线程池
配置如下:
1、添加全局@EnableAsync 注解,开启对异步的支持
@EnableAsync //开启对异步的支持
@Component
public class sopServiceRecoveryController {}
2、添加@Async 注解,将该定时任务设置成异步执行
@Async("executor1")
@Scheduled(cron = "0 0/5 * * * ?")
public void test01(){
logger.info("test01---"+new Date());
return;
}
@Async
@Scheduled(cron = "0 0/5 * * * ?")
public void test02(){
logger.info("test02---"+new Date());
return;
}
@Async
@Scheduled(cron = "0 0/5 * * * ?")
public void test03(){
logger.info("test03---"+new Date());
return;
}
①@Async(“executor1”)注解可配置进入的线程池名称
②该异步执行器每次都会开启一个子线程执行,性能消耗比较大,所以最好是自己配置线程池
3、配置线程池
使用@EnableAsync 注解,开启对异步的支持
@Configuration
@EnableAsync //开启对异步的支持
public class ThreadPoolTaskExecutorConfig {
//配置线程池--线程池01
@Bean
public Executor executor1() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("test-schedule1-");
executor.setMaxPoolSize(20);
executor.setCorePoolSize(15);
executor.setQueueCapacity(0);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
特别注意:
没有配置自己的线程池时,会默认使用SimpleAsyncTaskExecutor。