org.enodeframework.common.function.DelayedTask Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of enode Show documentation
Show all versions of enode Show documentation
The enodeframework core implementation.
package org.enodeframework.common.function;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.enodeframework.common.exception.EnodeInterruptException;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author [email protected]
*/
public class DelayedTask {
private static final ScheduledExecutorService EXECUTOR = new ScheduledThreadPoolExecutor(
1, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("DelayedThread-%d").build());
public static CompletableFuture startDelayedTaskFuture(Duration duration, Func action) {
CompletableFuture future = new CompletableFuture<>();
EXECUTOR.schedule(() -> future.complete(action.apply()), duration.toMillis(), TimeUnit.MILLISECONDS);
return future;
}
public static void startDelayedTask(Duration duration, Action action) {
DelayedTask.EXECUTOR.schedule(() -> {
try {
action.apply();
} catch (InterruptedException e) {
throw new EnodeInterruptException(e);
}
}, duration.toMillis(), TimeUnit.MILLISECONDS);
}
}