gpt4 book ai didi

带延迟的 Java 定时器永远不会运行

转载 作者:行者123 更新时间:2023-12-01 20:13:15 26 4
gpt4 key购买 nike

我有 java.util.Timer 类和 TimerTask 需要安排,我想每天凌晨 2 点执行该任务。

我的代码:

public class AutomaticPuller {

final private Timer t = new Timer();

public AutomaticPuller() {
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 2);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
long cooldown = today.getTimeInMillis();
if (today.getTime().before(new Date(System.currentTimeMillis()))) {
cooldown += 24L*60L*60L*1000L;
}
System.out.println("Task will run at: " + new Date(cooldown));
TimerTask tt = new TimerTask() {
public void run() {
try {
updateAll();
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.schedule(tt, cooldown, 24L*60L*60L*1000L);
}
}

我看到 println 的输出(任务将在:)运行,但应该在凌晨 2 点运行的任务从未执行,为什么?我不明白我从来没有遇到过这样的问题。输出日志中没有错误。

最佳答案

因为您使用今天的时间(以毫秒为单位)作为执行任务之前的延迟(以毫秒为单位)。这意味着该任务将在大约 47 年之后执行。

关于带延迟的 Java 定时器永远不会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46322562/

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