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;
    }
}
相关推荐
接着奏乐接着舞。几秒前
Go 一小时上手指南:从零到运行第一个程序
开发语言·后端·golang
河码匠5 分钟前
Django rest framework 自定义url
后端·python·django
JaguarJack10 分钟前
2026 年 PHP 8.4 依然重要:跳到 8.5 之前你该掌握的特性
后端·php·服务端
程序员爱钓鱼11 分钟前
Node.js 博客系统实战(一):项目需求分析
前端·后端·node.js
BingoGo12 分钟前
2026 年 PHP 8.4 依然重要:跳到 8.5 之前你该掌握的特性
后端·php
都叫我大帅哥1 小时前
Docker Swarm 部署方案
后端
都叫我大帅哥1 小时前
在Swarm中部署Nacos并配置外部MySQL
后端
想摆烂的不会研究的研究生8 小时前
每日八股——Redis(1)
数据库·经验分享·redis·后端·缓存
毕设源码-郭学长9 小时前
【开题答辩全过程】以 基于SpringBoot技术的美妆销售系统为例,包含答辩的问题和答案
java·spring boot·后端
追逐时光者9 小时前
精选 10 款 .NET 开源免费、功能强大的 Windows 效率软件
后端·.net