Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restart timer in java [duplicate]

Tags:

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!

like image 883
user1256477 Avatar asked Apr 26 '12 14:04

user1256477


People also ask

How do you repeat a timer in Java?

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.

How do you make a 1 second timer in Java?

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.

Does Java timer create a new thread?

yes,Java Timer object can be created to run the associated tasks as a daemon thread.


1 Answers

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 
like image 109
Eran Medan Avatar answered Oct 22 '22 03:10

Eran Medan