如何停止在Java.util.Timer类中安排的任务

om.*_*om. 84 java

我正在使用java.util.timer类,我正在使用它的调度方法来执行某些任务,但在执行它6次后,我必须停止它的任务.

我该怎么办?

Fri*_*z H 127

在某处保留对计时器的引用,并使用:

timer.cancel();
timer.purge();
Run Code Online (Sandbox Code Playgroud)

停止它正在做的事情.你可以把这个代码放在你正在执行的任务中,static int用来计算你去过的次数,例如

private static int count = 0;
public static void run() {
     count++;
     if (count >= 6) {
         timer.cancel();
         timer.purge();
         return;
     }

     ... perform task here ....

}
Run Code Online (Sandbox Code Playgroud)

  • 我认为取消就够了,不需要有清洗 (8认同)
  • @Jacky是对的.看看Timer的实现.取消后调用清除是绝对没用的.取消清除整个任务列表,同时清除迭代同一列表,检查状态是否为CANCELED,然后删除任务. (8认同)
  • 如果启动 Timer 的活动/片段被销毁或停止,Timer 是否会自行停止? (2认同)

Jon*_*eet 52

要么就是它正在进行cancel()Timer那么调用,要么cancel()就是TimerTask如果计时器本身还有其他你希望继续的任务.


Ver*_*ing 26

您应该停止在计时器上安排的任务:您的计时器:

Timer t = new Timer();
TimerTask tt = new TimerTask() {
    @Override
    public void run() {
        //do something
    };
}
t.schedule(tt,1000,1000);
Run Code Online (Sandbox Code Playgroud)

为了停止:

tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
Run Code Online (Sandbox Code Playgroud)

请注意,仅取消计时器不会终止正在进行的时间任务.


Abh*_*bhi 14

timer.cancel();  //Terminates this timer,discarding any currently scheduled tasks.

timer.purge();   // Removes all cancelled tasks from this timer's task queue.
Run Code Online (Sandbox Code Playgroud)