我想做一个计时器,当事情发生时它会重新启动:
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)
我不知道怎么办呢!谢谢!
答案 0 :(得分:13)
这对我来说很好......你能粘贴完整的代码和错误吗?
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: 123ipAddress:127.0.0.1 Updated timer
答案 1 :(得分:7)
每次重新启动Timer时都必须创建一个新的TimerTask对象。 所以,在Start上创建一个新的。并使用“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();
}
});