关于@Schedule任务结束前,下次是否启动实测

版权申明:本文为原创文章,转载请注明原文出处

原文链接:https://blog.it-follower.com/posts/2776241130.html

SpringBoot中使用@Scheduled(cron = “”)来标注一个定时任务,如果上一次任务尚未结束,但是已经到了下次任务的触发时间点了,那么这次任务是否会正常启动呢?本文将实测看个究竟

首先给出结论:上次未结束,下次任务不会启动。它会自动顺延到任务结束后的,下一个周期触发。

测试:

1、开始定时任务

1
2
3
4
5
6
7
8
9
10
11
@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的随机数。

下面看控制台打印效果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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秒打印的。也就是说,如果上一个任务结束时,刚好是下次任务的触发点,下次任务不会立马执行,而是会顺延到下一个周期

评论