java 如何判断Timer任务是否完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13721726/
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
How to determine whether the Timer task has completed
提问by Pavan
I have this following code :
我有以下代码:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
}
};
timer.schedule(task, 10000);//execute after 10 seconds
Can we determine whether the task is already executed by the timer or is still due?
我们可以确定任务是已经被定时器执行了还是仍然到期?
回答by DroidBender
Add a simple variable like..
添加一个简单的变量,如..
boolean isTaskCompleted = false;
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
// do stuff
isTaskCompleted = true;
}
};
timer.schedule(task, 10000);//execute after 10 seconds
回答by JustDanyul
Sure,
当然,
class CustomTask extends TimerTask {
protected boolean isDone = false;
public boolean isDone() {return isDone; }
@Override
public void run() {}
}
CustomTask task = new CustomTask() {
@Override
public void run() {
isDone=true;
}
};
EDIT: If you are not happy with extending the class, you could use the method scheduledExecutionTime(), this returns 0 if the task have not been run.
编辑:如果您对扩展类不满意,您可以使用方法 scheduleExecutionTime(),如果任务尚未运行,则返回 0。
http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html
http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html