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?
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, eg
private static int count = 0;
public static void run() {
count++;
if (count >= 6) {
timer.cancel();
timer.purge();
return;
}
... perform task here ....
}
无论是调用cancel()
的Timer
,如果这一切都在做,或cancel()
上TimerTask
如果计时器本身有您希望继续其它任务。
You should stop the task that you have 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);
In order to stop:
tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
Notice that just cancelling the timer will not terminate ongoing timertasks.
链接地址: http://www.djcxy.com/p/74900.html