Pausing/stopping and starting/resuming Java TimerTask continuously?

From TimerTask.cancel():

Note that calling this method from
within the run method of a repeating
timer task absolutely guarantees that
the timer task will not run again.

So once cancelled, it won’t ever run again. You’d be better off instead using the more modern ScheduledExecutorService (from Java 5+).

Edit: The basic construct is:

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(runnable, 0, 1000, TimeUnit.MILLISECONDS);

but looking into it there’s no way of cancelling that task once its started without shutting down the service, which is a bit odd.

TimerTask might be easier in this case but you’ll need to create a new instance when you start one up. It can’t be reused.

Alternatively you could encapsulate each task as a separate transient service:

final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
Runnable task1 = new Runnable() {
  public void run() {
    a++;
    if (a == 3) {
      exec.shutdown();
      exec = Executors.newSingleThreadScheduledExecutor();
      exec.scheduleAtFixedRate(task2, 0, 1000, TimeUnit.MILLISECONDS)
    }
  }
};
exec.scheduleAtFixedRate(task1, 0, 1000, TimeUnit.MILLISECONDS);

Leave a Comment