Pause the timer and then continue it

前端 未结 3 827
别那么骄傲
别那么骄傲 2020-12-01 12:58

Refer to the code that @Yuri posted from here. How to stop a timer after certain number of times . If I wanted to stop it because of some condition and then restart it agai

相关标签:
3条回答
  • 2020-12-01 13:26

    FIgured it out, it was because I didn't initialize the task in startManager()

    0 讨论(0)
  • 2020-12-01 13:27

    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 )

    0 讨论(0)
  • 2020-12-01 13:33

    There appears to be no way to do this: http://docs.oracle.com/javaee/6/api/javax/ejb/Timer.html

    You could likely cancel the timer, then create a new one.

    0 讨论(0)
提交回复
热议问题