1

I have a Timer that I scheduled a TimerTask with the delay 0 and the period 150. Now I want to change the period, but the Timer is already running. How can I change the period now?

private int penultimateStep = 1;
private int lastStep = 1;
private Timer move = new Timer();
private TimerTask movePlayer = new TimerTask(){
    public void run(){
        //Schritte ändern
        if(lastStep==3){
            lastStep = 2;
            penultimateStep = 1;
        }
        else if(lastStep==1){
            lastStep = 2;
            penultimateStep = 3;
        }
        else if(lastStep==2){
            if(penultimateStep==1){
                lastStep = 1;
                penultimateStep = 3;
            }
            else if(penultimateStep==3){
                lastStep = 3;
                penultimateStep = 1;
            }
        }
    }
};


...

move.schedule(movePlayer, 0, 150);
BhalchandraSW
  • 714
  • 5
  • 13

1 Answers1

-1

Timer and TimerTask - how to reschedule Timer from within TimerTask run

Resettable Java Timer

Check the two links. This question might be a duplicate of either of the above.

So you can modify your code as follows:

private int penultimateStep = 1;
private int lastStep = 1;
private Timer move = new Timer();

class MovePlayer extends TimerTask {
   public void run(){
       //Schritte ändern
       if(lastStep==3){
           lastStep = 2;
           penultimateStep = 1;
        }
        else if(lastStep==1){
            lastStep = 2;
            penultimateStep = 3;
        }
        else if(lastStep==2){
            if(penultimateStep==1){
                lastStep = 1;
                penultimateStep = 3;
            }
            else if(penultimateStep==3){
                lastStep = 3;
                penultimateStep = 1;
            }
        }
    }
}


...

move.schedule(new MovePlayer(), 0, 150);

Cheers.

Community
  • 1
  • 1
BhalchandraSW
  • 714
  • 5
  • 13