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

Peter picture Peter · Feb 1, 2014 · Viewed 10.5k times · Source

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.

Answer

user1445967 picture user1445967 · Feb 1, 2014

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?