最近在使用定时任务的时候发现,自己写的定时任务没有执行,后来查了上网查了一下,才知道@Scheduled注解的定时任务是单线程的,同一时间段内只能执行一个定时任务,其它定时任务不执行。
需要配置@Scheduled多线程支持,才能实现同一时间段内,执行多个定时任务。
一般情况下面两个定时任务只会执行第一个定时任务,第二个定时任务不会执行。
/**
* 测试定时任务1 每天22:00:00执行
*/
@Scheduled(cron = "0 0 22 * * ?")
public void test() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=======================测试定时任务执行1=======================");
}
}
/**
* 测试定时任务2 每天22:10:00执行
*/
@Scheduled(cron = "0 10 22 * * ?")
public void test2() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=======================测试定时任务执行2=======================");
}
}
要解决上诉问题,就需要配置 @Scheduled多线程支持,添加一个配置类,代码如下:
/**
* @description: 使@schedule支持多线程的配置类
* @author: David Allen
* @create: 2020-12-08
**/
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
Method[] methods = Job.class.getMethods();
int defaultPoolSize = 3;
int corePoolSize = 0;
if (!CollectionUtils.isEmpty(Arrays.asList(methods))) {
for (Method method : methods) {
Scheduled annotation = method.getAnnotation(Scheduled.class);
if (annotation != null) {
corePoolSize++;
}
}
if (defaultPoolSize > corePoolSize) {
corePoolSize = defaultPoolSize;
}
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize));
}
}
}
参考博客:https://blog.youkuaiyun.com/u012954380/article/details/92107902