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秒)。
- wait 60 sec.
- do task for some time (e.g. 40 - 100 sec).
- task finished.
- wait 60 seconds.
- do task for some time (e.g. 40 - 100 sec).
但上面的代码表现得像这样
But the code above behaves like this
- 等待60秒。
- 执行任务一段时间(例如40 - 100秒)。
- 任务完成
- 执行任务一段时间(例如40 - 100秒)。
- wait 60 sec.
- do task for some time (e.g. 40 - 100 sec).
- task finished
- do task for some time (e.g. 40 - 100 sec).
由于任务的持续时间大于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
用 60
s替换 10
s。
这篇关于java计时器任务计划的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!