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;
    }
}
相关推荐
吴佳浩6 小时前
Python入门指南(六) - 搭建你的第一个YOLO检测API
人工智能·后端·python
踏浪无痕7 小时前
JobFlow已开源:面向业务中台的轻量级分布式调度引擎 — 支持动态分片与延时队列
后端·架构·开源
Pitayafruit7 小时前
Spring AI 进阶之路05:集成 MCP 协议实现工具调用
spring boot·后端·llm
ss2738 小时前
线程池:任务队列、工作线程与生命周期管理
java·后端
不像程序员的程序媛8 小时前
Spring的cacheEvict
java·后端·spring
踏浪无痕8 小时前
JobFlow 实战:无锁调度是怎么做到的
后端·面试·架构
shoubepatien8 小时前
JAVA -- 11
java·后端·intellij-idea
喵个咪9 小时前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:kratos-bootstrap 入门教程(类比 Spring Boot)
后端·微服务·go
uzong9 小时前
从大厂毕业后,到小公司当管理,十年互联网老兵的思维习惯阶段复盘
后端
追逐时光者9 小时前
一个 WPF 开源、免费的 SVG 图像查看控件
后端·.net