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

查看:18
本文介绍了如何立即停止在 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.

推荐答案

Timer 无法停止任务.

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天全站免登陆