今天排查线上数据,发现数据并未更新,查看日志发现更新数据的定时任务并没有执行,而执行该定时任务的时间发现执行了另外的定时任务,所以因此初步判断可能是定时任务阻塞导致相同时间的定时任务有未执行任务。
写了个DEMO果真复现了,@Scheduled注解的定时任务为单线程执行,所以必定会有阻塞情况。
@Component
public class Test01 {
// 每秒执行一次
@Scheduled(cron = "0/1 * * * * ? ")
public void test() {
// 时分秒
String nowTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
// 日志打印
System.out.println(nowTime + " 任务【1】执行 线程:" + Thread.currentThread().getName());
}
}
@Component
public class Test02 {
// 每5秒执行一次
@Scheduled(cron = "0/5 * * * * ? ")
public void test() {
String nowTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(nowTime + " 任务【2】执行 线程:" + Thread.currentThread().getName());
try {
// 模拟耗时任务,阻塞2s
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
代码这里就不贴了,就是在上面的任务【1】和任务【2】的@Scheduled注解上面添加一个注解@Async即可。
很明显,任务【1】每秒执行的时间连续了!!!没有未执行的情况。
但需要注意的是,可以对@Async进行自定义配置,使其使用时,内部也是通过创建ThreadPoolExecutor线程池来执行。
原文:https://www.cnblogs.com/qukun/p/14889676.html