如何停止Java.util.Timer类中计划的任务


91

我正在使用java.util.timer类,并且正在使用其schedule方法执行某些任务,但是在执行了6次之后,我必须停止其任务。

我该怎么办?

Answers:


141

在某个地方保留对计时器的引用,并使用:

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

}

10
我认为取消就够了,不需要清除
LiangWang

1
根据(实用Java书籍)在final中添加timer.cancel()很好吗
Tushar Pandey

1
@Jacky拥有这两者是一个好习惯,但是从理论上讲,cancel它本身会起作用。
Fritz H

10
@杰基是对的。看一下Timer的实现。取消后调用清除绝对是没有用的。“取消”清除整个任务列表,而清除在同一列表上进行迭代,检查状态是否为“已取消”,然后删除任务。
博扬

2
如果启动计时器的活动/片段被破坏或停止,则计划的计时器是否会自行停止?
所有的


27

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

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

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


我有两种方法,是否可以从其他方法停止TimerTask?
Sachin HR

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

timer.purge();   // Removes all cancelled tasks from this timer's task queue.

1

在特定时间(毫秒)内唤醒后终止一次计时器。

Timer t = new Timer();
t.schedule(new TimerTask() {
            @Override
             public void run() {
             System.out.println(" Run spcific task at given time.");
             t.cancel();
             }
 }, 10000);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.