Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
354 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...