Question

I'm a novice at Java, and I've been trying to use java.util.timer to reset an existing timer after taking the right command input.

However, I've been unable to cancel the timertask properly, so the timer thread runs multiple instances of the timertask if the method is called multiple times. Any help would be appreciated.

Edit: I've changed the location of new Timer(), but it doesn't seem to have fixed it.

Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
    public void run() {
    System.out.println("ping");
    }   
};
public static void main (String[] args) {
    Timer timer = new Timer();

    while (true) {
      //BufferedReader to read input
      //Something
      if (input[0].equals("r")) {
         time t = new time();
         time.RestartTimer();
      }
    }
}
public void RestartTimer() {

        ttimer.cancel();
        timer.cancel();
        Timer timer = new Timer();
        TimerTask ttimer = new TimerTask() {
            public void run() {
            System.out.println("ping");
            }   
        };

        timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}    
Was it helpful?

Solution

This is happening because you are creating a new instance of time class (time t = new time(); ) inside the while loop. Instead do this :

 public static void main (String[] args) {

   time t = new time();  // create an instance of time class

   while (true) {
      //Something
      if (input[0].equals("r")) {
         // call RestartTimer on the same in
         t.RestartTimer();
      }
    }
 }

Also inside RestartTimer() function you are creating new instance of Timer. Change it as follows :

public void RestartTimer() {

    ttimer.cancel();
    timer.cancel();
    timer = new Timer();
    TimerTask ttimer = new TimerTask() {
        public void run() {
        System.out.println("ping");
        }   
    };

    timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}  

OTHER TIPS

time.RestartTimer(); statement won't be called until and unless either you change the modifier of method or call this method by using static object in main method. I think this is the only reason that your timer is not getting update.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top