In my Android application, I run a timer and cancel it on some other event:
class MyTimerTask extends TimerTask {
override boolean cancel() {
...
}
override void run() {
...
}
}
...
Timer t = new Timer();
t.schedule(new MyTimerTask(),...)
...
t.cancel();
I was expecting t.cancel()
to automatically invoke MyTimerTask
's cancel()
method. But that method is never invoked.
I am wondering what exactly is the different between these two methods and why the second method does not get called automatically.
Timer provides method to schedule Task where the task is an instance of TimerTask class, which implements the Runnable interface and overrides run() method to define task which is called on scheduled time.
Timer and TimerTask are java util classes that we use to schedule tasks in a background thread. Basically, TimerTask is the task to perform, and Timer is the scheduler.
The cancel() method is used to cancel the timer task. The cancel() methods returns true when the task is scheduled for one-time execution and has not executed until now and returns false when the task was scheduled for one-time execution and has been executed already.
The cancel() method of Timer class is used to terminate this timer and remove any currently scheduled tasks.
I think you meant to call cancel()
on your instance of MyTimerTask
Read the docs for this method...
http://developer.android.com/reference/java/util/TimerTask.html
public boolean cancel ()
Cancels the TimerTask and removes it from the Timer's queue. Generally, it returns false if the call did not prevent a TimerTask from running at least once. Subsequent calls have no effect.
http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#cancel
public void cancel()
Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.
Note that calling this method from within the run method of a timer task that was invoked by this timer absolutely guarantees that the ongoing task execution is the last task execution that will ever be performed by this timer.
This method may be called repeatedly; the second and subsequent calls have no effect.
Calling cancel()
on the timer stops it and removes all of its queued tasks. But there is no promise to call cancel()
on those tasks. Besides, would that make sense given that only 1 of those tasks could be running at any moment?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With