如何避免 @Scheduled 注释中的毫秒延迟?

问题描述 投票:0回答:1

我在工作中使用@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 spring-scheduled
1个回答
0
投票

根据您使用的 Spring 框架版本,无法保证毫秒级的精度。您的计算机内部时钟可能会因各种原因而发生漂移;这意味着 5 秒后安排下一个任务可能是正确的,但由于内部时钟的原因,执行发生的实际时间可能会有所不同。

从 Spring Framework 6.0.10 开始,Spring 为多种调度机制提供纳秒精度。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.