Java ScheduledExecutorService - 检查计划任务是否已经完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21442322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:44:46  来源:igfitidea点击:

ScheduledExecutorService - Check if scheduled task has already been completed

javamultithreadingtimersingleton

提问by markus

I have a server side application where clients can request to reload the configuration. If a client request to reload the configuration, this should not be done immediately, but with an delay of 1 minute. If another client also requests to reload the configuration in the same minute, this request should be ignored.

我有一个服务器端应用程序,客户端可以在其中请求重新加载配置。如果客户端请求重新加载配置,则不应立即执行此操作,而应延迟 1 分钟。如果同一分钟内另一个客户端也请求重新加载配置,则应忽略此请求。

My idea is to schedule a task with a ScheduledExecutorService like:

我的想法是使用 ScheduledExecutorService 安排任务,例如:

 ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
 service.schedule(new LoadConfigurationTask(), 1, TimeUnit.MINUTES);

 public class LoadConfigurationTask Runnable {
    public void run() {
      // LoadConfiguration
    }
 }

How can I check if a LoadConfigurationTask has been scheduled, but not executed yet, to be able to ignore further requests until the configuration is reloaded ?

如何检查 LoadConfigurationTask 是否已安排但尚未执行,以便能够在重新加载配置之前忽略进一步的请求?

采纳答案by Tim B

The easiest way is just to set an AtomicBooleanhttp://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html

最简单的方法是设置一个AtomicBooleanhttp://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html

Set it to true when you launch the task, set it to false when the task finishes, don't launch any more unless it is on false.

启动任务时将其设置为true,任务完成时将其设置为false,除非为false,否则不要再启动。

Make sure you do the setting to false in a finally block so you can't accidentally exit without un-setting it.

确保在 finally 块中将设置设置为 false,这样您就不会在不取消设置的情况下意外退出。

回答by Minh-Triet Lê

You can simply get a reference to a ScheduledFuture like this:

您可以像这样简单地获得对 ScheduledFuture 的引用:

ScheduledFuture<?> schedFuture = service.schedule(new LoadConfigurationTask(), 1, TimeUnit.MINUTES);

Now with the future, you can check if the task is done:

现在有了未来,您可以检查任务是否已完成:

schedFuture.isDone();

Or even better, check how much time left before the execution will begin:

或者更好的是,检查执行开始前还剩多少时间:

schedFuture.getDelay(TimeUnit.MINUTES);

There is no need for external variable to track the state.

不需要外部变量来跟踪状态。