I would like to do a timer, it will be restarted when something happens:
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);
}
I have a problem when I create the new schedule, I have this error:
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)
I don't know how can I do it! Thanks!
解决方案
This works fine for me... can you paste the full code and error?
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);
}
}
This outputs:
MAC: 123ipAddress:127.0.0.1
Updated timer