@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
结论:上次未结束,下次任务不会启动。它会自动顺延到任务结束后的,下一个周期触发