java - Java 中 ScheduledExecutorService 的时间一致性问题

标签 java scheduledexecutorservice

我尝试使用 ScheduledExecutorService 每 15 分钟调用一次可运行的任务。这些任务应该在以下时间每小时运行一次: 第 2 分钟 10 秒 第 17 分 10 秒 第 32 分 10 秒 第 47 分第 10 秒。

我使用 Calendar 实例计算第一次执行任务的初始延迟,然后使用 scheduleAtFixedRate() 的延迟每 15 分钟执行一次任务。这在最初几天工作正常,但几天后我可以观察到任务执行的时间偏移。例如,应该在 12:02:10 开始的任务在 12:03:45 被调用。我哪里出错了?

public static void main(String[] args) {    
  final ScheduledExecutorService scheduler = Executors
                .newScheduledThreadPool(15);
  Date aDate = new Date();
  Calendar cal = Calendar.getInstance();
  cal.setTime(aDate);
  int currentHour = cal.get(Calendar.HOUR_OF_DAY);
  int currentMins = cal.get(Calendar.MINUTE);
  int currentSecs = cal.get(Calendar.SECOND);
  int unitInSecs;      
  int delayFor15MinTasksInSecs;
  unitInSecs = currentMins * 60 + currentSecs;
  delayFor15MinTasksInSecs = unitInSecs < (3 * 60 - 50 ) ? (3 * 60 - 50 ) - unitInSecs : unitInSecs < (18 * 60 - 50 ) ? (18 * 60 - 50 ) - unitInSecs : unitInSecs < (33 * 60 - 50 ) ? (33 * 60 - 50 ) - unitInSecs : unitInSecs < (48 * 60 - 50 )? (48 * 60 - 50 ) - unitInSecs : (63 *60 - 50 ) - unitInSecs;
  scheduler.scheduleAtFixedRate(new RTPAcquiringTask(10), delayFor15MinTasksInSecs, 15*60, TimeUnit.SECONDS);
}

最佳答案

此 API 在计时方面并不完美。

来自 ScheduledExecutorService 的 Javadoc :

Beware however that expiration of a relative delay need not coincide with the current Date at which the task is enabled due to network time synchronization protocols, clock drift, or other factors.

关于java - Java 中 ScheduledExecutorService 的时间一致性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34803032/

相关文章:

java - getResourceAsStream 在尝试检索 JSON 文件时使用 android 返回 null

java - executor.shutdown()的使用

java - JSVC Java Daemon 需要改进性能

Java:执行Runnable固定次数

java - 无法增加 java 堆大小

java - 离线使用的 JUnit5 javadocs

java - 如何使用 ScheduledExecutorService 通过多个服务定期运行作业

java - 在变化数量的线程中并发重复相同的任务

java - 如何让 Jersey Test/Client 不填写默认的 Accept header ?

java - JUnit 测试意外行为