我相信你想要的是ScheduledExecutorService
其 schedule
方法接受一個延遲參數。該延遲可以在不同的TimeUnit
數量中指定,例如納秒,秒,小時等。
該想法是計算在某些時間單位(例如秒)期望的執行日期和當前時間之間的差異。
這是一個應該給你一個線索(Java 8)的片段。
public class App {
public static void main(String[] args) {
final Runnable jobToExecute =() -> System.out.println("Doing something on " + new Date());
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
ScheduledFuture future = executorService.schedule(jobToExecute, diffInSeconds(LocalDateTime.of(2017, 5, 30, 23, 54, 00)), TimeUnit.SECONDS);
}
private static long diffInSeconds(LocalDateTime dateTime) {
return dateTime.toEpochSecond(ZoneOffset.UTC) - LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
}
}
您可以通過由ScheduledExecutorService::schedule
方法返回的ScheduledFuture
對象跟蹤作業的完成狀態。
是的,這是正確的。 但我正在尋找的是保持實例在我的後端服務器上。而且你也可以改變日期或取消。 – marlonpya
@marlonpya ScheduledExecutorService :: schedule返回['ScheduledFuture'](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledFuture.html)。您可以使用該對象來檢查作業的狀態。 –
如果今天我在ScheduledExecutorService上做。那麼明天mayben我想取消這個計劃或改變如何得到特定的對象? – marlonpya