【问题标题】:Java - change the duration of Timer while it is runningJava - 在运行时更改 Timer 的持续时间
【发布时间】:2017-06-22 09:28:02
【问题描述】:

我有一个Timer,我安排了一个TimerTaskdelay 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);

【问题讨论】:

标签: java timer timertask


【解决方案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);

干杯。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多