1

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

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

RemoteSync实现了AutoCloseable(and Runnable) 接口,所以我最初使用try-with-resources的是 ,像这样:

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

但是updater.startService()在调度任务后立即返回,因此updater.close()被提前调用并且应用程序退出。

下面是startService()方法RemoteSync

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

但这感觉肮脏和骇人听闻。

欢迎任何建议。

4

2 回答 2

1

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

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

Runtime.getRuntime().addShutdownHook(new Thread() {
  public void run() {
    >>> shutdown your service here <<<
  }
});
于 2015-05-14T11:44:08.497 回答
0

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

于 2015-05-07T12:57:29.980 回答