有什么方法可以在 Java 中调度 CompletableFuture 吗? 我想做的是安排一个任务以一定的延迟执行,并在它完成时将其与其他异步执行的操作链接起来。到目前为止,我还没有找到任何方法来做到这一点。
对于良好的 future ,我们有例如ScheduledExecutorService,我们可以在其中安排一个任务以像这样的延迟执行:
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
Future<String> future = scheduledExecutorService.schedule(() -> "someValue", 10, TimeUnit.SECONDS);
CompletableFutures有没有类似的方法?
最佳答案
如果您使用的是 Java 9+,则 CompletableFuture#delayedExecutor(long,TimeUnit)
可能满足您的需求:
Returns a new Executor that submits a task to the default executor after the given delay (or no delay if non-positive). Each delay commences upon invocation of the returned executor's
execute
method.
Executor delayed = CompletableFuture.delayedExecutor(10L, TimeUnit.SECONDS);
CompletableFuture.supplyAsync(() -> "someValue", delayed)
.thenAccept(System.out::println)
.join();
还有 an overload您可以在其中指定 Executor
来代替“默认执行程序”。
关于java - 是否可以安排 CompletableFuture?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58707689/