How to interrupt a ScheduledExecutorService

让人想犯罪 __ 提交于 2019-12-11 06:19:08

问题


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?


回答1:


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.




回答2:


scheduleAtFixedRate() returns a ScheduledFuture which is a Future which has the cancel method you're looking for.



来源:https://stackoverflow.com/questions/45439694/how-to-interrupt-a-scheduledexecutorservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!