Java - Timer.cancel() v/s TimerTask.cancel() Java - Timer.cancel() v/s TimerTask.cancel() android android

Java - Timer.cancel() v/s TimerTask.cancel()


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?