How to stop immediately the task scheduled in Java

2019-01-25 19:47发布

问题:

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:

  1. I schedule Timer like this:

    timer.schedule(timerTask, 60 * 1000);

  2. 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.

回答1:

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.



回答2:

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.