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

Java-ScheduledExecutorService:在终止时执行任务,java,executorservice,autocloseable,Java,Executorservice,Autocloseable,我使用ScheduledExecutorService以固定速率执行任务。以下是我的主要方法的内容: RemoteSync updater = new RemoteSync(config); try { updater.initialise(); updater.startService(totalTime, TimeUnit.MINUTES); } catch (Exception e) { e.printStackTrace(); } RemoteSync实现了A

我使用
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();
}
while (!scheduledExecutorService.isTerminated()) {
    Thread.sleep(10000);
}
但是
updater.startService()
在调度任务后立即返回,因此
updater.close()
被过早调用,应用程序退出

以下是
RemoteSync
startService()
方法:

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()
方法:

try (RemoteSync updater = new RemoteSync(config)) {
    ...
} catch (Exception e) {
   e.printStackTrace();
}
while (!scheduledExecutorService.isTerminated()) {
    Thread.sleep(10000);
}
但这感觉又脏又粗糙


欢迎您提出任何建议。

您可以尝试
scheduledExecutorService.WaitTermination(Long.MAX\u值,TimeUnit.ms),
可能在单独的线程中

您可以使用应用程序关闭挂钩。喜欢讨论

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

Runtime.getRuntime().addShutdownHook(新线程(){
公开募捐{

>>>在这里关闭你的服务也许你可以使用应用程序关闭钩子。就像在讨论中一样。嗯,我听说过关闭钩子。我会试试的。谢谢@nukie@nukie我最终使用了一个关机钩子,如果你愿意添加一个我会接受的答案。这似乎是一个不错的选择,唯一的问题是没有设置超时。应用程序可能会运行数天甚至几周。我能做的就是检查服务是否已经终止。如果没有(发生超时),我可以再次致电
waittermination
。不过谢谢你的建议。