Java 延迟计时器从不运行
Java timer with delay never runs
我有 java.util.Timer class 和 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 的输出(任务将 运行 at:) 但应该在凌晨 2 点 运行 的任务从未执行过,为什么?我不明白我从来没有遇到过这样的问题。输出日志中没有错误。
因为您使用今天的时间(以毫秒为单位)作为执行任务之前的延迟时间(以毫秒为单位)。这意味着该任务将在大约 47 年后执行。
通过添加此行修复:
cooldown = cooldown - System.currentTimeMillis();
基本上我只是忘了从冷却时间中删除当前毫秒。
我有 java.util.Timer class 和 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 的输出(任务将 运行 at:) 但应该在凌晨 2 点 运行 的任务从未执行过,为什么?我不明白我从来没有遇到过这样的问题。输出日志中没有错误。
因为您使用今天的时间(以毫秒为单位)作为执行任务之前的延迟时间(以毫秒为单位)。这意味着该任务将在大约 47 年后执行。
通过添加此行修复:
cooldown = cooldown - System.currentTimeMillis();
基本上我只是忘了从冷却时间中删除当前毫秒。