How to stop a task scheduled in the Java.util.Timer class

I use the java.util.timer class, and I use its schedule method to perform some task, but after it is done 6 times, I have to stop my task.

How should I do it?

+61
java
Sep 11 '09 at 5:23
source share
5 answers

Keep the timer link somewhere and use:

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

to stop everything he does. You can put this code inside the task you are doing with a static int to count the number of times you went, for example.

 private static int count = 0; public static void run() { count++; if (count >= 6) { timer.cancel(); timer.purge(); return; } ... perform task here .... } 
+94
Sep 11 '09 at 5:28
source share

Either call cancel() in Timer if that is all it does, or cancel() in TimerTask if the timer itself has other tasks that you want to continue.

+42
Sep 11 '09 at 5:26
source share

You must stop the task that you 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); 

To stop:

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

Please note that only canceling the timer will not stop the current tasks.

+13
Jun 18 '13 at 14:29
source share
 timer.cancel(); //Terminates this timer,discarding any currently scheduled tasks. timer.purge(); // Removes all cancelled tasks from this timer task queue. 
+9
Jan 29 '15 at 11:56
source share

End the timer once after waking up 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); 
+1
Oct 08 '16 at 17:10
source share



All Articles