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

JavaTimer

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 ....

}
    

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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

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

Solution 5 - Java

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionom.View Question on Stackoverflow
Solution 1 - JavaFritz HView Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - JavaVeringView Answer on Stackoverflow
Solution 4 - JavaAbhiView Answer on Stackoverflow
Solution 5 - JavaAjay KumarView Answer on Stackoverflow