Reputation: 47
I have a ScheduledExecutorService
that I am using to run a method updateIndex()
every one minute. However, if changes to resources are made during the one minute between the last refresh and the next refresh, I would like to have updateIndex()
called immediately, and then have the executor service resume it's normal schedule; i.e. next update will take place in one minute. However, I haven't seen anything in the documentation to suggest there is the capability to do this. Any ideas?
Upvotes: 1
Views: 2706
Reputation: 457
scheduleAtFixedRate()
returns a ScheduledFuture which is a Future which has the cancel
method you're looking for.
Upvotes: 1
Reputation: 568
public static void updateIndex() {
Runnable runnable = () -> {
//Do your logic here
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.MINUTES);
}
According to JavaDocs
java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor. If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
Upvotes: 1