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!
Use timer. scheduleAtFixedRate() to schedule it to recur every two seconds: Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
You can start the timer with one of the schedule methods like this: timer. schedule(new TimerTask() { @Override public void run() { //do your stuff here... } }, 0, 1000); This will start your timer with a delay of 0 milliseconds and repeat it after 1000 milliseconds.
yes,Java Timer object can be created to run the associated tasks as a daemon thread.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With