如何立即停止在Java.util.Timer类中安排的任务 [英] How to stop immediately the task scheduled in Java.util.Timer class

查看:79
本文介绍了如何立即停止在Java.util.Timer类中安排的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了一切.这也是如何停止Java.util.Timer类中安排的任务

I tried everything. This one too How to stop the task scheduled in Java.util.Timer class

我有一个实现java.util.TimerTask的任务

I have one task that implements java.util.TimerTask

我通过两种方式调用该任务:

I call that task in 2 ways:

  1. 我安排如下计时器:

  1. I schedule Timer like this:

timer.schedule(timerTask,60 * 1000);

timer.schedule(timerTask, 60 * 1000);

有时我需要立即启动该工作,并且如果有正在工作的工作,则必须取消timerTask

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);

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)

但是我需要它停止.

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();
 }
}

计时器中是否有一种方法可以停止当前正在执行的任务,例如Thread.kill()之类的东西?当我需要停止该任务时,我希望它失去所有数据.

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.

推荐答案

计时器无法在其轨道上停止任务.

There is no way for the Timer to stop the task in its tracks.

您将需要在正在运行的任务本身中具有一种单独的机制,该机制可以检查它是否应该继续运行.例如,您可以有一个 AtomicBoolean keepRunning 变量,当您希望任务终止时将其设置为false.

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.

这篇关于如何立即停止在Java.util.Timer类中安排的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆