java定时器任务调度 [英] java timer task schedule
问题描述
从 Stack Overflow 上的阅读来看,我看到你们中的许多人不推荐使用 Timer Task.嗯...但我已经实现了这个:
From reading on Stack Overflow I've seen that many of you don't recommend using Timer Task. Hmmm... but I already implemented this:
我有这个代码:
detectionHandlerTimer.schedule(myTimerTask, 60 * 1000, 60 * 1000);
问题是 myTimerTask 的工作会持续一段时间.
The thing is that work of myTimerTask lasts some time.
我想要这种行为:
- 等待 60 秒.
- 完成一段时间的任务(例如 40 - 100 秒).
- 任务完成.
- 等待 60 秒.
- 完成一段时间的任务(例如 40 - 100 秒).
但是上面的代码是这样的
But the code above behaves like this
- 等待 60 秒.
- 完成一段时间的任务(例如 40 - 100 秒).
- 任务完成
- 完成一段时间的任务(例如 40 - 100 秒).
由于任务的持续时间大于60,定时器在任务完成后立即启动任务.但我希望它再等一次.
Because the time duration of task is bigger than 60, timer starts task immediately after task is finished. But I would like it to wait again.
推荐答案
这有效.关键是让任务本身(完成后)安排任务的下一次发生.
This works. The key is to have the task itself (after it completes) schedule the next occurrence of the task.
import java.util.Timer;
import java.util.TimerTask;
public class TaskManager {
private Timer timer = new Timer();
public static void main(String[] args) {
TaskManager manager = new TaskManager();
manager.startTask();
}
public void startTask() {
timer.schedule(new PeriodicTask(), 0);
}
private class PeriodicTask extends TimerTask {
@Override
public void run() {
System.out.println(System.currentTimeMillis() + " Running");
/* replace with the actual task */
try {
Thread.sleep(15 * 1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
/* end task processing */
System.out.println(System.currentTimeMillis() + " Scheduling 10 seconds from now");
timer.schedule(new PeriodicTask(), 10 * 1000);
}
}
}
打印:
$ javac TaskManager.java && java TaskManager
1288282514688 Running
1288282529711 Scheduling 10 seconds from now
1288282539712 Running
1288282554713 Scheduling 10 seconds from now
1288282564714 Running
如果您提取时间戳的第二个组成部分(为了清楚起见),则如下所示:
Here's what it looks like if you extract the second components of the timestamps (for clarity):
$ javac TaskManager.java && java TaskManager
14 Running
29 (+15 seconds execution) Scheduling 10 seconds from now
39 (+10 seconds delay until next run) Running
54 (+15 seconds execution) Scheduling 10 seconds from now
64 (+10 seconds delay until next run) Running
只需将 10
替换为 60
即可.
Just replace the 10
s with 60
s.
这篇关于java定时器任务调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!