1 回答

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
ScheduledExecutorService
您可以使用自 Java 5 起可用的ScheduledExecutorService( documentation ) 類。它將產(chǎn)生一個(gè)ScheduledFuture( documentation ),可用于監(jiān)視執(zhí)行并取消它。
具體來(lái)說(shuō),方法:
ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
哪個(gè)
提交在給定延遲后啟用的一次性任務(wù)。
但是您也可以查看其他方法,具體取決于實(shí)際用例(scheduleAtFixedRate以及接受Callable而不是 的版本Runnable)。
由于 Java 8 (Streams, Lambdas, ...) 這個(gè)類變得更加方便,因?yàn)門imeUnit新舊ChronoUnit(對(duì)于你的ZonedDateTime)之間的簡(jiǎn)單轉(zhuǎn)換方法的可用性,以及提供Runnable commandas lambda 或方法的能力參考(因?yàn)樗?a FunctionalInterface)。
例子
讓我們看一個(gè)執(zhí)行您要求的示例:
// Somewhere before the method, as field for example
// Use other pool sizes if desired
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
public static ScheduledFuture<?> scheduleFor(Runnable runnable, ZonedDateTime when) {
Instant now = Instant.now();
// Use a different resolution if desired
long secondsUntil = ChronoUnit.SECONDS.between(now, when.toInstant());
return scheduler.schedule(runnable, secondsUntil, TimeUnit.of(ChronoUnit.SECONDS));
}
調(diào)用很簡(jiǎn)單:
ZonedDateTime when = ...
ScheduledFuture<?> job = scheduleFor(YourClass::yourMethod, when);
然后,您可以使用job來(lái)監(jiān)視執(zhí)行并在需要時(shí)取消它。例子:
if (!job.isCancelled()) {
job.cancel(false);
}
筆記
ZonedDateTime您可以將方法中的參數(shù)交換為Temporal,然后它還接受其他日期/時(shí)間格式。
完成后不要忘記關(guān)閉ScheduledExecutorService。否則,即使您的主程序已經(jīng)完成,您也會(huì)有一個(gè)線程正在運(yùn)行。
scheduler.shutdown();
請(qǐng)注意,我們使用Instant而不是ZonedDateTime,因?yàn)閰^(qū)域信息與我們無(wú)關(guān),只要正確計(jì)算時(shí)間差即可。Instant始終代表 UTC 時(shí)間,沒(méi)有像DST這樣的奇怪現(xiàn)象。(雖然對(duì)于這個(gè)應(yīng)用程序來(lái)說(shuō)并不重要,但它更干凈)。
添加回答
舉報(bào)