ScheduledExecutorService - Check if scheduled task

2019-01-20 12:18发布

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.

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
    }
 }

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 ?

2条回答
孤傲高冷的网名
2楼-- · 2019-01-20 13:03

The easiest way is just to set an AtomicBoolean http://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.

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

查看更多
我只想做你的唯一
3楼-- · 2019-01-20 13:03

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

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.

查看更多
登录 后发表回答