ScheduledExecutorService - 检查计划任务是否已经完成 [英] ScheduledExecutorService - Check if scheduled task has already been completed

查看:28
本文介绍了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,除非设置为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.

这篇关于ScheduledExecutorService - 检查计划任务是否已经完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆