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