Pause the timer and then continue it

If you have already canceled one timer, you can’t re-start it, you’ll have to create a new one.

See this answer, it contains a video and the source code how I did something similar.

Basically there are two method: pause and resume

In pause:

public void pause() {
    this.timer.cancel();
}

In resume:

public void resume() {
    this.timer = new Timer();
    this.timer.schedule( aTask, 0, 1000 );
}

That makes the perception of pause/resume.

If your timers perform different actions based on the state of the application you may consider use the StatePattern

Fist define a abstract state:

abstract class TaskState  {
    public void run();
    public TaskState next();
}

And provide as many states as you like. The key is that one state leads you to another.

class InitialState extends TaskState {
    public void run() {
        System.out.println( "starting...");
    }
    public TaskState next() {
         return new FinalState();
    }
 }
 class FinalState extends TaskState  {
     public void run() {
         System.out.println("Finishing...");
     }
     public TaskState next(){
         return new InitialState();
    }
 }

And then you change the state in your timer.

Timer timer = new Timer();
TaskState state = new InitialState();

timer.schedule( new TimerTask() {
     public void run() {
          this.state.run();
          if( shouldChangeState() ) {
              this.state = this.state.next();
           }
     }
 }, 0, 1000 );

Finally, if what you need is to perform the same thing, but at different rates, you may consider using the TimingFramework. It is a bit more complex but let’s you do cool animations, by allowing the painting of certain component take place at different rates ( instead of being linear )

Leave a Comment