1、使用@Scheduled注解创建两个任务测试运行
@Scheduled(cron = "0 0/1 * * * ?")
public void test1() {
log.info(Thread.currentThread().getName() + "- Scheduled1");
try {
Thread.sleep(1000 * 30);
} catch (InterruptedException e) {
}
log.info(Thread.currentThread().getName() + "- Scheduled1");
}
@Scheduled(cron = "0 0/1 * * * ?")
public void test2() {
log.info(Thread.currentThread().getName()+"-Scheduled2");
try {
Thread.sleep(1000 * 40);
} catch (InterruptedException e) {
}
log.info(Thread.currentThread().getName()+"-Scheduled2");
}
2、不做任何配置直接执行
2023-11-17 10:31:00.009 INFO 15660 --- [pool-1-thread-1] c.v.j.modules.controller.TestController : pool-1-thread-1-Scheduled2
2023-11-17 10:31:40.020 INFO 15660 --- [pool-1-thread-1] c.v.j.modules.controller.TestController : pool-1-thread-1-Scheduled1
2023-11-17 10:32:10.030 INFO 15660 --- [pool-1-thread-1] c.v.j.modules.controller.TestController : pool-1-thread-1-Scheduled2
2023-11-17 10:33:00.014 INFO 15660 --- [pool-1-thread-1] c.v.j.modules.controller.TestController : pool-1-thread-1-Scheduled1
3、配置ScheduledExecutorService线程池执行
/**
* 执行周期性或定时任务
*/
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() {
return new ScheduledThreadPoolExecutor(10,
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
new ThreadPoolExecutor.CallerRunsPolicy()) {
};
}
2023-11-17 10:35:00.009 INFO 9588 --- [schedule-pool-2] c.v.j.modules.controller.TestController : schedule-pool-2-Scheduled2
2023-11-17 10:35:00.009 INFO 9588 --- [schedule-pool-1] c.v.j.modules.controller.TestController : schedule-pool-1-Scheduled1
2023-11-17 10:36:00.005 INFO 9588 --- [schedule-pool-1] c.v.j.modules.controller.TestController : schedule-pool-1-Scheduled1
2023-11-17 10:36:00.005 INFO 9588 --- [schedule-pool-3] c.v.j.modules.controller.TestController : schedule-pool-3-Scheduled2
4、结论
在不做配置的情况下,定时任务执行使用的线程是同一个(pool-1-thread-1),效率低下,当其中一个任务阻塞时,无法继续执行其他任务,或当前任务执行时间超过调度周期,也无法在下一周期时间立即执行任务;
修改Bean对象,配置ScheduledExecutorService线程池,可以开启多线程执行定时任务,在资源足够时不会相互影响,也不会;
建议 使用springboot项目时对ScheduledExecutorService线程池做自定义配置;