Reputation: 358
I have a background task that I run using the ScheduledThreadPoolExecutor with code like this.
executor.scheduleWithFixedDelay(new BackgroundSync(), 0, 15, TimeUnit.MINUTES);
BackgroundSync implements Runnable.
Sometimes from a user event I want the delayed event to run now and not when the 15 minute timer goes off.
Some requirements:
Upvotes: 0
Views: 1010
Reputation: 718698
Kabuko's solution is probably as good as you will get, but there is a snag.
The cancel()
method returns true
if the task was cancelled before it started, and false
if the task has already run, or if it was previously cancelled. The problem is that if the task is currently running, cancel()
will return true
. Thus you need to implement some other mechanism to decide whether or not to resubmit the task.
Upvotes: 2
Reputation: 36302
scheduleWithFixedDelay returns a ScheduledFuture. When calling it, store this somewhere and check if it exists if you want to do the immediate execution. Then you can cancel the scheduled future using the cancel method and schedule your runnable again for immediate execution.
Upvotes: 2