顾名思义,我们有一个守护进程框架,它使用Executor服务来安排守护进程。
java.util.concurrent.ScheduledThreadPoolExecutor.scheduleWithFixedDelay(Runnable
command, long initialDelay, long delay, TimeUnit unit)
在运行时,我想更改Runnable
类的两次运行之间的延迟,而不会终止我们的应用程序。
有可能吗?如果是,怎么样?
答案 0 :(得分:3)
我不知道提前的最小粒度
在这种情况下,您需要取消计划并重新添加。
private Future future = null;
private long periodMS = 0;
public void setPeriod(long periodMS) {
if (future != null && this.periodMS == periodMS) return;
if (future != null) future.cancel(false);
scheduledExecutorService.scheduleWithFixedDelay(task, periodMS/2, periodMS, TimeUnit.MILLI_SECONDS);
}
或者您可以让任务自行重新安排。
private long periodMS;
public void start() {
scheduledExecutorService.schedule(this, periodMS, TimeUnit.MILLI_SECONDS);
}
public void run() {
try {
task.run();
} catch(Exception e) {
// handle e
}
start();
}
这样一段时间可以在每次运行时改变。