How to stop TimerTask already in execution?

How to stop a running TimerTask

I have gone through the above link and my problem didn't solve completely.

We can stop a Timer, by calling timerObj.cancel() . The documentation of cancel method clearly says:

Cancels the {@code Timer} and all scheduled tasks. If there is a currently running task it is not affected . No more tasks may be scheduled on this {@code Timer}. Subsequent calls do nothing

So my question/concern here is,

If lot of TimerTasks were scheduled under a timer , How could we stop all of them even If they are executing their respective run methods ? Is there a way to solve this?

Thanks in advance.


You should design the run method so that it can determine for itself when to terminate, for example by polling the state of an AtomicBoolean.

Even if you were to find the thread running the TimerTask, calling stop() or similar methods upon the thread would be inherently unsafe.

链接地址: http://www.djcxy.com/p/74916.html

上一篇: 暂停计时器,然后继续

下一篇: 如何停止已经执行的TimerTask?