两个Scheduled几乎同一时间执行.如果某一个定时任务执行时间比较长,会导致另一个任务执行失败?
根本问题是Scheduled是单线程执行任务的
//出问题代码
@Scheduled(cron = "0/5 * * * * ?")
public void test1() throws InterruptedException {
Thread.sleep(10000); //模拟复杂任务
log.info("定时任务1: 当前线程 {}", Thread.currentThread().getName());
}
@Scheduled(cron = "0/5 * * * * ?")
public void test2() throws InterruptedException {
Thread.sleep(10000); //模拟复杂任务
log.info("定时任务2,当前线程 {}", Thread.currentThread().getName());
}
启动异步线程池来解决问题:
1.定义线程池
@Configuration
@Slf4j
public class AsyncThreadPoolConfig {
@Bean("asyncThreadPoolTaskExecuter")
public Executor ThreadPoolTaskExecuter() {
int coreNum = Runtime.getRuntime().availableProcessors();
log.info("cpu数量 {}", coreNum);
ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
threadPoolExecutor.setCorePoolSize(coreNum);
threadPoolExecutor.setThreadNamePrefix("aysc_thread_");
threadPoolExecutor.setMaxPoolSize(2*coreNum);
threadPoolExecutor.setQueueCapacity(20);
threadPoolExecutor.setKeepAliveSeconds(10);
threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return threadPoolExecutor;
}
}
2.springBoot启动类注解
@EnableAsync // 开启异步请求注解
@EnableScheduling
3.业务代码
@Scheduled(cron = "0/5 * * * * ?")
@Async("asyncThreadPoolTaskExecuter")
public void test1() throws InterruptedException {
Thread.sleep(10000); //模拟复杂任务
log.info("定时任务1: 当前线程 {}", Thread.currentThread().getName());
}
@Scheduled(cron = "0/5 * * * * ?")
@Async("asyncThreadPoolTaskExecuter")
public void test2() throws InterruptedException {
Thread.sleep(10000); //模拟复杂任务
log.info("定时任务2,当前线程 {}", Thread.currentThread().getName());
}