10

我有以下代码:

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

我们可以确定任务是已经被定时器执行了还是到期了?

4

2 回答 2

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
于 2012-12-05T11:03:34.430 回答
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;
    }
 };

编辑:如果您对扩展类不满意,您可以使用方法 scheduleExecutionTime(),如果任务尚未运行,则返回 0。

http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html

于 2012-12-05T11:03:49.787 回答