java定时器任务调度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4044729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java timer task schedule
提问by vale4674
From reading on Stack Overflow I've seen that many of you don't recommend using Timer Task. Hmmm... but I already implemented this:
通过阅读 Stack Overflow,我发现你们中的许多人不建议使用 Timer Task。嗯......但我已经实现了这个:
I have this code:
我有这个代码:
detectionHandlerTimer.schedule(myTimerTask, 60 * 1000, 60 * 1000);
The thing is that work of myTimerTask lasts some time.
问题是 myTimerTask 的工作会持续一段时间。
I would like this behavior:
我想要这种行为:
- 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).
- 等待 60 秒。
- 做一段时间的任务(例如 40 - 100 秒)。
- 任务完成。
- 等待 60 秒。
- 做一段时间的任务(例如 40 - 100 秒)。
But the code above behaves like this
但是上面的代码表现得像这样
- 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 秒。
- 做一段时间的任务(例如 40 - 100 秒)。
- 任务完成
- 做一段时间的任务(例如 40 - 100 秒)。
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.
由于任务的持续时间大于60,任务完成后定时器立即启动任务。但我希望它再次等待。
采纳答案by Rob Hruska
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);
}
}
}
Which prints:
哪个打印:
$ 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
Just replace the 10
s with 60
s.
只需将10
s替换为60
s。