All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.enodeframework.common.function.DelayedTask Maven / Gradle / Ivy

There is a newer version: 1.1.10
Show newest version
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);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy