tags:

views:

404

answers:

3

Hello, 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 ?

+1  A: 

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.

Jon Skeet
Thanks Jon,let me check this
om
+3  A: 

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

}
Fritz H
Thanks Fritz H, let me try this in my code.
om
Hey its working in my code, thanks very much
om
Cool! Great to hear, and happy to have helped. :) Cheers
Fritz H
A: 

/*deleted*/

vale4674