Java – How to stop immediately the task scheduled in Java.util.Timer class


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

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

This implementation just cancels the timer but leaves currently doing task to be finished.

public static void cancelCurrentwork() {
 if (timer!= null) {

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.

Best Solution

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.