views:

36

answers:

2

I tried everything. This one too http://stackoverflow.com/questions/1409116/how-to-stop-the-task-scheduled-in-java-util-timer-class/4047921#4047921

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.

+2  A: 

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.

aioobe
And how to stop the work from inside the Task? I could check with boolean, but what method should I call then? this.cancel()?
vale4674
And other question: does any API like ScheduledExecutorService or something like that allows you to STOP task?
vale4674
No, you simply return from the `run` method.
aioobe
Yes that looks like it will do the trick. But it's not that "elegant". Because my run() method contains few methods and each of them require some time to work. Some of them don't have while loops in it to check that boolean constantly. So as you see, I need it to stop immediately, not after task realizes that boolean is set to false.
vale4674
If there is a blocking method, you would have to `interrupt` it.
aioobe
Did that, than I just catch that exception and return from run(). Thank you.
vale4674
A: 

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.

MeBigFatGuy