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
Author by
Pavan
Updated on July 20, 2022Comments
-
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 over 11 yearsi 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 over 11 yearsthanks.. but android doc for scheduledExecutionTime() says this : Tasks which have not yet run return an undefined value. developer.android.com/reference/java/util/…
-
JustDanyul over 11 yearsjava 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 over 7 yearsThis 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.