CompletableFuture 延时执行任务

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;
    }
}
相关推荐
像风一样自由202019 分钟前
Go语言详细指南:特点、应用场景与开发工具
开发语言·后端·golang
IT_陈寒1 小时前
《Java 21新特性实战:5个必学的性能优化技巧让你的应用快30%》
前端·人工智能·后端
choice of1 小时前
SpringMVC通过注解实现全局异常处理
java·后端·spring
单线程bug1 小时前
Spring Boot中Filter与Interceptor的区别
java·spring boot·后端
小蒜学长1 小时前
基于uni-app的蛋糕订购小程序的设计与实现(代码+数据库+LW)
java·数据库·spring boot·后端·小程序·uni-app
程序员爱钓鱼1 小时前
Go语言实战案例 — 工具开发篇:Go 实现条形码识别器
后端·google·go
期待のcode9 小时前
Spring框架1—Spring的IOC核心技术1
java·后端·spring·架构
Livingbody10 小时前
10分钟完成 ERNIE-4.5-21B-A3B-Thinking深度思考模型部署
后端
胡萝卜的兔11 小时前
go 日志的分装和使用 Zap + lumberjack
开发语言·后端·golang
en-route11 小时前
如何在 Spring Boot 中指定不同的配置文件?
java·spring boot·后端