我有以下代码:
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
我们可以确定该任务是否已经由计时器执行或者是否仍然有效?
答案 0 :(得分:6)
添加一个简单的变量,如..
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
答案 1 :(得分:3)
当然,
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;
}
};
编辑: 如果您对扩展类不满意,可以使用scheduledExecutionTime()方法,如果任务尚未运行,则返回0。
http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html