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

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

I have one task that implements java.util.TimerTask

I invoke this task in two ways:

  • I plan Timer as follows:

    timer.schedule (timerTask, 60 * 1000);

  • sometimes i need this job to start immediately and it should cancel timerTask if there is one working

    cancelCurrentWork (); timer.schedule (timerTask, 0);

This implementation does not stop the current work: (the documentation says: if the task is executed when this call occurs, the task will be completed, but will never be started again)

But I need him to stop.

public static void cancelCurrentwork() {
 if (timerTask!= null) {
  timerTask.cancel();
 }
}

This implementation simply cancels the timer, but leaves the execution of the current task.

public static void cancelCurrentwork() {
 if (timer!= null) {
  timer.cancel();
 }
}

STOP taks, Thread.kill() - ? , , .

+5
2

.

, , . , AtomicBoolean keepRunning, false, .

+5

- / .., , , .

- , /.

0

All Articles