我有一个定时器例程,我想每两个小时执行一次。但是我下面的逻辑似乎执行得太早了。有谁知道我做错了什么?
(new Timer()).scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
try
{
//TODO: Perform routine.
}
catch (Exception ex)
{
try
{
throw ex;
}
catch (Exception e)
{
}
}
}
}, 0, (1000 * 60 * 120));
谢谢。
最佳答案
根据javadoc ,您的代码应立即触发例程(初始延迟为零),然后每 2 小时(120 分钟)。
scheduleAtFixedRate(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
如果你想在 2 小时后第一次触发,那么做
long interval = 1000 * 60 * 120;
scheduleAtFixedRate(task, interval, interval)
关于java - 每 2 小时执行一次 Java 定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6372221/