om. om. - 2 months ago 8
Java Question

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?

Answer

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

}