[英]How to decide if java.util.Timer is running
I write my own Timer
class, which fires a single execution of TimerTask
. 我编写了自己的Timer
类,它触发了TimerTask
的单次执行。 In my singleton Timer , there is private boolean isRunning
. 在我的单例Timer中 ,有一个private boolean isRunning
。 If isRunning==true
, other threads won't fire the Timer. 如果isRunning==true
,则其他线程不会触发Timer。
public class DBconnectDelayTimer extends Timer {
/**
* Indicates if the Timer is running
*/
private boolean isRunning;
public DBconnectDelayTimer() {
super();
isRunning = false;
}
@Override
public void schedule(TimerTask task, long delay)
isRunning = true;
super.schedule(task, delay);
}
public boolean isRunning() {
return isRunning;
}
}
My question is, in which method should I set isRunning
back to false
? 我的问题是,应使用哪种方法将isRunning
设置为false
?
Thank you for any help. 感谢您的任何帮助。
One naive solution is to wrap the task argument in another task that resets isRunning
upon completion: 一个幼稚的解决方案是将task参数包装到另一个在完成时重置isRunning
任务中:
@Override
public void schedule(TimerTask task, long delay) {
isRunning = true;
super.schedule(new TimerTask() {
@Override
public void run() {
task.run();
isRunning = false;
}
}, delay);
}
Note that this only works if no more than one task is scheduled at a time, which is difficult to enforce without proper synchronization. 请注意,这仅在一次安排不超过一个任务的情况下才有效,如果没有适当的同步,则很难执行。 It also breaks Timer
's promise to throw an IllegalStateException
if a single task is scheduled twice. 如果单个任务被调度两次,它也会破坏Timer
的抛出IllegalStateException
的承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.