首先给出结论:上次未结束,下次任务不会启动。它会自动顺延到任务结束后的,下一个周期触发。
测试:
1、开始定时任务
@Scheduled(cron = "0/3 * * * * ? ")
public void run() {
int sleep = new Random().nextInt(10);
log.info("say sleep: {}s", sleep);
try {
Thread.sleep(sleep * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
任务设定的是,从0秒开始,每3秒钟执行一次。任务耗时通过线程sleep来模拟,时长则是一个0-10的随机数。
下面看控制台打印效果:
2019-03-01 14:25:24 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 9s
2019-03-01 14:25:36 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 7s
2019-03-01 14:25:45 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 9s
2019-03-01 14:25:57 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 4s
2019-03-01 14:26:03 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 2s
2019-03-01 14:26:06 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 8s
2019-03-01 14:26:15 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 0s
2019-03-01 14:26:18 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 2s
2019-03-01 14:26:21 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 9s
2019-03-01 14:26:33 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 1s
2019-03-01 14:26:36 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 1s
2019-03-01 14:26:39 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 0s
2019-03-01 14:26:42 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 3s
2019-03-01 14:26:48 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 4s
2019-03-01 14:26:54 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 4s
2019-03-01 14:27:00 INFO 8008 --- [ scheduling-1] c.yclouds.service.demo.TestJob : say sleep: 3s
2、结果分析
line1和line2对比:24秒执行的任务,耗时9秒。line2并没有在27秒执行打印,说明上次任务未结束时,下次任务不会启动。
line1和line2对比:理论上line1会在33秒时结束,此时刚好下次任务的触发点,结果可以看出,line2并不是在33秒执行的打印,而是下一个周期36秒打印的。也就是说,如果上一个任务结束时,刚好是下次任务的触发点,下次任务不会立马执行,而是会顺延一个周期