CompletableFuture 延时执行任务
java
public class TestMain {
private static ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
public static void main(String[] args) {
CompletableFuture<String> future = delayedFuture(() -> {
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "hello world";
}, 3, TimeUnit.SECONDS);
future.whenComplete((result, throwable) -> {
if (throwable == null) {
System.out.println(result);
} else {
System.out.println(throwable.getMessage());
}
});
try {
Thread.sleep(10000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
int i = 0;
}
public static <T> CompletableFuture<T> delayedFuture(Supplier<T> supplier, long delay, TimeUnit unit) {
CompletableFuture<T> future = new CompletableFuture<>();
scheduler.schedule(() -> {
try {
future.complete(supplier.get());
} catch (Exception e) {
future.completeExceptionally(e);
}
}, delay, unit);
return future;
}
}