23

我想做一个计时器,当有事情发生时它会重新启动:

public static Timer timer;

public myTimer(long MAC, String ipAddress){
    timer = new Timer();
    timer.schedule(timerTask, 120000); 
}

public void update(){
    timer.cancel();
    timer = new Timer();
    timer.schedule(timerTask, 120000); 
}  

创建新计划时遇到问题,出现以下错误:

java.lang.IllegalStateException: Task already scheduled or cancelled
    at java.util.Timer.sched(Timer.java:358)
    at java.util.Timer.schedule(Timer.java:170)
    at spb.keepAliveTimer.update(keepAliveTimer.java:37)
    at spb.keepAlive.update(keepAlive.java:58)
    at spb.receptor.keepAlive(receptor.java:475)
    at spb.receptor.run(receptor.java:118)
    at java.lang.Thread.run(Thread.java:662)

我不知道我该怎么做!谢谢!

4

2 回答 2

16

这对我来说很好......你能粘贴完整的代码和错误吗?

package snippet;

import java.util.Timer;
import java.util.TimerTask;

public class Main {
    public static Timer timer;

    public static void main(String[] args) {
        Main main = new Main();
        main.myTimer(123, "127.0.0.1");


    }

    public void myTimer(final long MAC, final String ipAddress) {
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                System.out.println("MAC: " + MAC + "ipAddress:" + ipAddress);
                update();
            }
        };
        timer = new Timer();
        timer.schedule(timerTask, 1000);

    }

    public void update() {
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                System.out.println("Updated timer");

            }
        };
        timer.cancel();
        timer = new Timer();
        timer.schedule(timerTask, 2000);
    }
}

这输出:

MAC:123ip地址:127.0.0.1
 更新计时器
于 2012-04-26T14:56:33.050 回答
8

每次重新启动 Timer 时,都必须创建一个新的 TimerTask 对象。所以,在开始时创建一个新的。并使用“Timer.cancel”和“Timer.purge”销毁计时器。

例如,我有两个按钮 - 开始和停止

mStartButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mTimerTask = new TimerTask();//This creates new TimerTask 
timer = new Timer(); //Instantiate again, as we Cancel the Timer
timer.schedule(mTimerTask, 0, 30);
}
});

mEndButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
timer.cancel();
timer.purge();
}
});
于 2015-04-29T17:17:38.193 回答