SpringBoot - @Schedule 上次任务未结束,下次任务到时间是否会启动验证

2023-12-13 07:00:29

任务案例?

@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

结果分析?

  • line1和line2对比:24秒执行的任务,耗时9秒。line2并没有在27秒执行打印,说明上次任务未结束时,下次任务不会启动
  • line1和line2对比:理论上line1会在33秒时结束,此时刚好下次任务的触发点,结果可以看出,line2并不是在33秒执行的打印,而是下一个周期36秒打印的。也就是说,如果上一个任务结束时,刚好是下次任务的触发点,下次任务不会立马执行,而是会顺延一个周期
  • 结论:上次未结束,下次任务不会启动。它会自动顺延到任务结束后的,下一个周期触发

文章来源:https://blog.csdn.net/Dream_Weave/article/details/134949695
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。