gpt4 book ai didi

Java-ScheduledExecutorService : Execute task at termination

转载 作者:行者123 更新时间:2023-11-30 08:12:57 26 4
gpt4 key购买 nike

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

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

RemoteSync 实现了 AutoCloseable (和 Runnable)接口(interface),因此我最初使用 try-with-resources ,像这样:

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

但是 updater.startService() 在调度任务后立即返回,因此 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);
}

但这感觉又脏又黑。

欢迎任何建议。

最佳答案

也许您可以使用应用程序关闭 Hook 。就像this讨论。

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

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

关于Java-ScheduledExecutorService : Execute task at termination,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30101177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com