如何停止在 java.util.Timer 类中调度的任务

我使用的是 java.util.Timer类,我使用它的调度方法来执行一些任务,但在执行了6次之后,我不得不停止它的任务。

我该怎么做?

213477 次浏览

Either call ABC0 on the Timer if that's all it's doing, or ABC0 on the TimerTask if the timer itself has other tasks which you wish to continue.

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


}

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.

Terminate the Timer once after awake at a specific time in milliseconds.

Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);