Here you can find the source of delayedFuture(Duration delay, ScheduledExecutorService executorService)
Parameter | Description |
---|---|
delay | The duration of the delay (how much to wait until completing the Future). |
executorService | An ExecutorService that will be used to complete the Future on. |
public static CompletableFuture<Void> delayedFuture(Duration delay, ScheduledExecutorService executorService)
//package com.java2s; /**/*from w ww . j ava2 s .co m*/ * Copyright (c) 2017 Dell Inc., or its subsidiaries. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; public class Main { /** * Creates a CompletableFuture that will do nothing and complete after a specified delay, without using a thread during * the delay. * * @param delay The duration of the delay (how much to wait until completing the Future). * @param executorService An ExecutorService that will be used to complete the Future on. * @return A CompletableFuture that will complete after the specified delay. */ public static CompletableFuture<Void> delayedFuture(Duration delay, ScheduledExecutorService executorService) { CompletableFuture<Void> result = new CompletableFuture<>(); if (delay.toMillis() == 0) { // Zero delay; no need to bother with scheduling a task in the future. result.complete(null); } else { ScheduledFuture<Boolean> sf = executorService.schedule(() -> result.complete(null), delay.toMillis(), TimeUnit.MILLISECONDS); result.whenComplete((r, ex) -> sf.cancel(true)); } return result; } /** * Executes the asynchronous task after the specified delay. * * @param task Asynchronous task. * @param delay Delay in milliseconds. * @param executorService Executor on which to execute the task. * @param <T> Type parameter. * @return A CompletableFuture that will be completed with the result of the given task. */ public static <T> CompletableFuture<T> delayedFuture(final Supplier<CompletableFuture<T>> task, final long delay, final ScheduledExecutorService executorService) { return delayedFuture(Duration.ofMillis(delay), executorService).thenCompose(v -> task.get()); } }