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

问题描述:

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

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.

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

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

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

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

我如何检查LoadConfigurationTask是否已被调度但尚未执行,以便能够在重新加载配置之前忽略其他请求?

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 ?

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

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

启动任务时将其设置为true,将其设置为false任务完成,不要再启动,除非它是假的。

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.

确保你在finally块中设置为false,这样你就不会意外退出取消它。

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