![](/img/trans.png)
[英]How to stop immediately the task scheduled in Java.util.Timer class
[英]How to stop the task scheduled in java.util.Timer class
我正在使用java.util.Timer
class 我正在使用它的調度方法來執行一些任務,但是在執行了 6 次之后我不得不停止它的任務。
我該怎么做?
在某處保留對計時器的引用,並使用:
timer.cancel();
timer.purge();
停止它正在做的任何事情。 您可以將此代碼放在您使用static int
執行的任務中,以計算您四處走動的次數,例如
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
如果計時器本身有您希望繼續其它任務。
您應該停止您在計時器上安排的任務:您的計時器:
Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
//do something
};
}
t.schedule(tt,1000,1000);
為了停止:
tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
請注意,僅取消計時器不會終止正在進行的計時器任務。
timer.cancel(); //Terminates this timer,discarding any currently scheduled tasks.
timer.purge(); // Removes all cancelled tasks from this timer's task queue.
在以毫秒為單位的特定時間喚醒后終止 Timer 一次。
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.