How to determine whether the Timer task has completed

17,833

Solution 1

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

Solution 2

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.

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

Share:
17,833
Pavan
Author by

Pavan

Updated on July 20, 2022

Comments

  • Pavan
    Pavan almost 2 years

    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?

  • Pavan
    Pavan over 11 years
    i know about this workaround.. But problem here is that isDone() cannot be called explicitly unless you extend TimerTask. But i wanted to know if there is any api from TimerTask for this..
  • Pavan
    Pavan over 11 years
    thanks.. but android doc for scheduledExecutionTime() says this : Tasks which have not yet run return an undefined value. developer.android.com/reference/java/util/…
  • JustDanyul
    JustDanyul over 11 years
    java doesn't have an "undefined" type, and the method declaration shows it will return a long, hence it cant be null. This undefined value is 0. Try it :)
  • Anand
    Anand over 7 years
    This is a good idea! But When I call the same task from multiple times for multiple purposes. However, I have different timer variables to cancel different tasks. How can I find that the task corresponding to that perticular timer is running or not.