如何立即停止Java.util.Timer类中安排的任务
我尝试了一切。这也是如何停止Java.util.Timer 类中计划的任务
我有一个实现 java.util.TimerTask 的任务,
我以两种方式调用该任务:
我这样安排 Timer:
timer.schedule(timerTask, 60 * 1000);
有时我需要立即开始这项工作,并且如果有任何正在工作的计时器任务,则必须取消该任务
取消当前工作(); timer.schedule(timerTask, 0);
此实现不会停止当前工作: (文档说:如果发生此调用时任务正在运行,则任务将运行至完成,但永远不会再次运行)
但我需要它停止。
public static void cancelCurrentwork() {
if (timerTask!= null) {
timerTask.cancel();
}
}
此实现只是取消计时器,但让当前正在执行的任务完成。
public static void cancelCurrentwork() {
if (timer!= null) {
timer.cancel();
}
}
计时器中有没有办法停止当前正在执行的任务,例如 Thread.kill() 之类的?当我需要停止该任务时,我希望它丢失所有数据。
I tried everything. This one too How to stop the task scheduled in Java.util.Timer class
I have one task that implements 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);
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
计时器无法停止任务的运行。
您需要在正在运行的任务本身中有一个单独的机制来检查它是否应该继续运行。例如,您可以有一个 AtomicBoolean keepRunning 变量,当您希望任务终止时将其设置为 false。
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.如果您的计时器正在使用某种文件/套接字等,您可以从计时器外部关闭该对象,并且计时器任务将引发异常,您可以使用它来停止计时器。
但一般来说,您需要某种毒丸才能成功停止单独的线程/计时器。
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.