Java - ScheduledExecutorService:在终止时执行任务

Java - ScheduledExecutorService: Execute task at termination

我使用ScheduledExecutorService以固定速率执行任务。这是我的主要方法的内容:

RemoteSync updater = new RemoteSync(config);
try  {
    updater.initialise();
    updater.startService(totalTime, TimeUnit.MINUTES);
} catch (Exception e) {
    e.printStackTrace();
}

RemoteSync实现了AutoCloseable(和Runnable)接口,所以我一开始使用try-with-resources,像这样:

try (RemoteSync updater = new RemoteSync(config)) {
    ...
} catch (Exception e) {
   e.printStackTrace();
}

但是 updater.startService() returns 在调度任务后立即执行,因此 updater.close() 被过早调用并且应用程序退出。

这里是RemoteSyncstartService()方法:

public void startService(int rate, TimeUnit unit) {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    service =
        scheduledExecutorService.scheduleWithFixedDelay(this, 1L,
        rate,
        unit);
}

理想情况下,我想要一个像这样的方法:

scheduledExecutorService.executeAtTermination(Runnable task)

这将允许我在调度程序实际停止时调用 close(),不幸的是我不知道这种方法。

我能做的就是阻止 startService() 方法,像这样:

while (!scheduledExecutorService.isTerminated()) {
    Thread.sleep(10000);
}

但这感觉很脏而且很老套。

欢迎提出任何建议。

您可以尝试 scheduledExecutorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS), 可能在单独的线程中

也许您可以使用应用程序关闭钩子。就像在 this 讨论中一样。

您可以在应用程序初始化的某个阶段添加这样的代码:

Runtime.getRuntime().addShutdownHook(new Thread() {
  public void run() {
    >>> shutdown your service here <<<
  }
});