我在工作中使用@Scheduled来实现一些简单的定时任务,例如:
private static long pre = System.currentTimeMillis();
@Scheduled(fixedRate = 5000L)
public void testScheduled() {
System.out.println(System.currentTimeMillis());
long cur = System.currentTimeMillis();
long gap = cur - pre;
pre = cur;
}
理论上我认为gap的值应该是5000? …… 但现实中他会有几毫秒的误差,甚至十几毫秒的误差,我也尝试过用
ScheduledThreadPoolExecutor
来调度,但是结果是一样的
我对计划任务了解不够,但我想知道原因是什么,请帮帮我!
根据您使用的 Spring 框架版本,无法保证毫秒级的精度。您的计算机内部时钟可能会因各种原因而发生漂移;这意味着 5 秒后安排下一个任务可能是正确的,但由于内部时钟的原因,执行发生的实际时间可能会有所不同。