gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:11:01 25 4
gpt4 key购买 nike

我尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com