Java - 在运行时更改Timer的持续时间

时间:2017-02-05 10:14:19

标签: java timer timertask

我有一个Timer我计划了一个TimerTask delay 0和period 150。 现在我要更改period,但Timer已在运行。 如何更改period现在?

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);

1 个答案:

答案 0 :(得分:-1)

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

Resettable Java Timer

检查两个链接。这个问题可能与上述任何一个都重复。

因此您可以按如下方式修改代码:

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);

干杯。