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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1409116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:45:43  来源:igfitidea点击:

How to stop the task scheduled in Java.util.Timer class

java

提问by om.

I am using java.util.timerclass and I am using its schedule method to perform some task, but after executing it for 6 times I have to stop its task.

我正在使用java.util.timerclass 并且我正在使用它的 schedule 方法来执行一些任务,但是在执行它 6 次后我必须停止它的任务。

How should I do that?

我该怎么做?

采纳答案by Fritz H

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 intto count the number of times you've gone around, e.g.

停止它正在做的任何事情。您可以将此代码放在您正在执行的任务中,static int以计算您四处走动的次数,例如

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

     ... perform task here ....

}

回答by Jon Skeet

Either call cancel()on the Timerif that's all it's doing, or cancel()on the TimerTaskif the timer itself has other tasks which you wish to continue.

无论是通话cancel()Timer,如果这一切都在做,或者cancel()TimerTask如果定时器本身有您希望继续其它任务。

回答by Vering

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.

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

回答by Abhi

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

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

回答by Ajay Kumar

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

在以毫秒为单位的特定时间唤醒后终止 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);