简体   繁体   English

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

[英]Java timer with delay never runs

I have java.util.Timer class and TimerTask to schedule, I want to do the task every day at 2AM. 我要安排java.util.Timer类和TimerTask,我想每天凌晨2点执行任务。

My code: 我的代码:

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);
    }
}

I see the output from println (Task will run at:) but the task that should run at 2AM is never executed, why ? 我看到了println的输出(任务将在以下位置运行),但是应在2AM运行的任务却从未执行过,为什么? I dont get it I have never met such a problem. 我不明白,我从未遇到过这样的问题。 No errors in output log. 输出日志中没有错误。

Because you are using todays time in milliseconds as the delay in milliseconds before task is to be executed. 因为您使用今天的时间(以毫秒为单位)作为执行任务之前的延迟(以毫秒为单位)。 That means the task will execute in about 47 years. 这意味着任务将在大约47年内执行。

Fixed by adding this line: 通过添加此行来修复:

cooldown = cooldown - System.currentTimeMillis();

Basically I just forgot to remove the current millis from the cooldown. 基本上,我只是忘了从冷却中删除当前的毫。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM