[英]ScheduledExecutorService - Check if scheduled task has already been completed
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.
如果客户端请求重新加载配置,则不应立即执行此操作,但延迟时间为1分钟。 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安排任务,如:
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是否已被调度但尚未执行,以便能够忽略进一步的请求,直到重新加载配置为止?
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. 不需要外部变量来跟踪状态。
The easiest way is just to set an AtomicBoolean
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html 最简单的方法就是设置
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. 在启动任务时将其设置为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,这样您就不会在不取消设置的情况下意外退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.