Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

timer

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?

like image 635
om. Avatar asked Sep 11 '09 05:09

om.


People also ask

How do I stop Java util timer?

timer. cancel(); //Terminates this timer,discarding any currently scheduled tasks. timer. purge(); // Removes all cancelled tasks from this timer's task queue.

How does Java util timer work?

Timer Class in Java. Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions.

What is delay in timer Java?

Timers are constructed by specifying both a delay parameter and an ActionListener . The delay parameter is used to set both the initial delay and the delay between event firing, in milliseconds. Once the timer has been started, it waits for the initial delay before firing its first ActionEvent to registered listeners.


1 Answers

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 ....  } 
like image 138
Fritz H Avatar answered Oct 01 '22 12:10

Fritz H