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;
    }
}
相关推荐
IT_陈寒2 分钟前
JavaScript的this坑人实录,这次我真的记下来了
前端·人工智能·后端
starzy19901 小时前
Scala类和对象:从构造器到样例类的完整指南
开发语言·后端·scala
梦影_1 小时前
MySQL进阶教程(五)—— SQL调优(下)
android·大数据·数据库·后端·sql·mysql·database
考虑考虑1 小时前
mariadb数据库
数据库·后端·mariadb
明月_清风2 小时前
用自然语言操控真机:Google Artemis 移动端 AI Agent 上手与实践
人工智能·后端
怪我冷i2 小时前
Rust 的impl语法详解
开发语言·后端·rust
我就是全世界2 小时前
OpenCode Go 套餐划算吗:先看你用哪个模型
开发语言·后端·golang
乌暮3 小时前
请求进门先安检:Spring 拦截器与统一功能实战指南
java·开发语言·后端·学习·spring
学长毕设3 小时前
基于SpringBoot的烘焙商品商品系统-附源码
java·spring boot·后端
付威20234 小时前
Durable Execution 怎样设计:从运行记录到中断恢复
后端