如何立即停止在 Java.util.Timer 类中安排的任务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4050442/
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
How to stop immediately the task scheduled in Java.util.Timer class
提问by vale4674
I tried everything. This one too How to stop the task scheduled in Java.util.Timer class
我尝试了一切。这个也是如何停止Java.util.Timer类中调度的任务
I have one task that implements java.util.TimerTask
我有一项实现 java.util.TimerTask 的任务
I call that task in 2 ways:
我以两种方式调用该任务:
I schedule Timer like this:
timer.schedule(timerTask, 60 * 1000);
sometimes I need that work to start immediately and it has to cancel timerTask if there is any that is working
cancelCurrentWork(); timer.schedule(timerTask, 0);
我这样安排计时器:
timer.schedule(timerTask, 60 * 1000);
有时我需要立即开始这项工作,如果有任何工作,它必须取消 timerTask
取消当前工作();timer.schedule(timerTask, 0);
This implementation doesn't stop current work: (documentation says: If the task is running when this call occurs, the task will run to completion, but will never run again)
此实现不会停止当前的工作:(文档说:如果发生此调用时任务正在运行,则任务将运行完成,但永远不会再次运行)
But I need it to stop.
但我需要它停下来。
public static void cancelCurrentwork() {
if (timerTask!= null) {
timerTask.cancel();
}
}
This implementation just cancels the timer but leaves currently doing task to be finished.
这个实现只是取消了计时器,但让当前正在执行的任务完成。
public static void cancelCurrentwork() {
if (timer!= null) {
timer.cancel();
}
}
Is there a way in timer to STOP current executing taks, something like Thread.kill() or something? When I need that task to stop I want it to loose all its data.
有没有办法在计时器中停止当前正在执行的任务,例如 Thread.kill() 之类的?当我需要停止该任务时,我希望它丢失所有数据。
回答by aioobe
There is no way for the Timer to stop the task in its tracks.
计时器无法在其轨道上停止任务。
You will need to have a separate mechanism in the running task itself, that checks if it should keep running. You could for instance have an AtomicBoolean keepRunning
variable which you set to false when you want the task to terminate.
您将需要在正在运行的任务本身中有一个单独的机制,以检查它是否应该继续运行。例如AtomicBoolean keepRunning
,当您希望任务终止时,您可以将一个变量设置为 false。
回答by MeBigFatGuy
if your timer is using some sort of file/socket etc, you can close that object from outside the timer, and the timer task will throw an exception, and you can use it to stop the timer.
如果您的计时器正在使用某种文件/套接字等,您可以从计时器外部关闭该对象,计时器任务将引发异常,您可以使用它来停止计时器。
but in general you need some sort of poison pill to successfully stop a separate thread/timer.
但总的来说,您需要某种毒丸才能成功停止单独的线程/计时器。