ScheduledExecutorService, how to stop action without stopping executor?
Asked Answered
M

2

9

I have this code:

ScheduledExecutorService scheduledExecutor;
.....
ScheduledFuture<?> result = scheduledExecutor.scheduleWithFixedDelay(
    new SomethingDoer(),0, measurmentPeriodMillis, TimeUnit.MILLISECONDS);

After some event I should stop action, which Declared in run() method of the SomethingDoer, which implements Runnable.

How can I do this? I can't shutdown executor, I should only revoke my periodic task. Can I use result.get() for this? And if I can, please tell me how it will work.

Messier answered 2/7, 2013 at 7:2 Comment(0)
H
15

Use result.cancel(). The ScheduledFuture is the handle for your task. You need to cancel this task and it will not be executed any more.

Actually, cancel(boolean mayInterruptIfRunning) is the signature and using it with true parameter will cause a currently running exection's thread to be interrupted with the interrupt() call. This will throw an interrupted exception if the thread is waiting in a blocking interruptible call, like Semaphore.acquire(). Keep in mind that cancel will ensure only that the task will not be executed any more once it stopped the execution.

Hyrcania answered 2/7, 2013 at 7:26 Comment(0)
P
6

You can use the cancel() method from your ScheduledFuture object. Once cancelled, no further tasks will be executed.

If you want your currently running task to stop, you need to code your run method so it is sensitive to interrupts and pass true to the cancel() method to request an interrupt.

Paraph answered 2/7, 2013 at 7:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.