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?
timer. cancel(); //Terminates this timer,discarding any currently scheduled tasks. timer. purge(); // Removes all cancelled tasks from this timer's task queue.
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.
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.
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 .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With