[java] How to stop the task scheduled in java.util.Timer class

I am using java.util.Timer class and I am using its schedule method to perform some task, but after executing it for 6 times I have to stop its task.

How should I do that?

This question is related to java timer

The answer is


Keep a reference to the timer somewhere, and use:

timer.cancel();
timer.purge();

to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.

private static int count = 0;
public static void run() {
     count++;
     if (count >= 6) {
         timer.cancel();
         timer.purge();
         return;
     }

     ... perform task here ....

}

timer.cancel();  //Terminates this timer,discarding any currently scheduled tasks.

timer.purge();   // Removes all cancelled tasks from this timer's task queue.

You should stop the task that you have scheduled on the timer: Your timer:

Timer t = new Timer();
TimerTask tt = new TimerTask() {
    @Override
    public void run() {
        //do something
    };
}
t.schedule(tt,1000,1000);

In order to stop:

tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread

Notice that just cancelling the timer will not terminate ongoing timertasks.


Either call cancel() on the Timer if that's all it's doing, or cancel() on the TimerTask if the timer itself has other tasks which you wish to continue.


Terminate the Timer once after awake at a specific time in milliseconds.

Timer t = new Timer();
t.schedule(new TimerTask() {
            @Override
             public void run() {
             System.out.println(" Run spcific task at given time.");
             t.cancel();
             }
 }, 10000);