@
pkwenda key 不是随机的,同一个周期计算得到的是固定的值,这样通过 key 就保证了加的锁只锁定当前周期,不会因为时间的误差而影响到下个周期定时任务的执行,你可以执行下这段代码看下 nextTime 的计算结果:
```java
@
Test public void testNextTime() throws Exception {
CronSequenceGenerator c = new CronSequenceGenerator("0/5 * * * * ?");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
for (int i = 0; i < 100; i++) {
Date now = new Date();
long nextTime = c.next(now).getTime();
System.out.println(format.format(now) + " 的 nextTime 为:" + nextTime);
Thread.sleep(1000);
}
}
```
我执行的结果:
2022-09-05 10:52:11.011 的 nextTime 为:1662346335000
2022-09-05 10:52:12.012 的 nextTime 为:1662346335000
2022-09-05 10:52:13.013 的 nextTime 为:1662346335000
2022-09-05 10:52:14.014 的 nextTime 为:1662346335000
2022-09-05 10:52:15.015 的 nextTime 为:1662346340000
2022-09-05 10:52:16.016 的 nextTime 为:1662346340000
2022-09-05 10:52:17.017 的 nextTime 为:1662346340000
2022-09-05 10:52:18.018 的 nextTime 为:1662346340000
2022-09-05 10:52:19.019 的 nextTime 为:1662346340000
2022-09-05 10:52:20.020 的 nextTime 为:1662346345000
2022-09-05 10:52:21.021 的 nextTime 为:1662346345000
2022-09-05 10:52:22.022 的 nextTime 为:1662346345000
2022-09-05 10:52:23.023 的 nextTime 为:1662346345000
2022-09-05 10:52:24.024 的 nextTime 为:1662346345000
2022-09-05 10:52:25.025 的 nextTime 为:1662346350000
2022-09-05 10:52:26.026 的 nextTime 为:1662346350000
2022-09-05 10:52:27.027 的 nextTime 为:1662346350000