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;
    }
}
相关推荐
Tony Bai4 小时前
【Go开发者的数据库设计之道】07 诊断篇:SQL 性能诊断与问题排查
开发语言·数据库·后端·sql·golang
花花鱼5 小时前
spring boot项目使用tomcat发布,也可以使用Undertow(理论)
spring boot·后端·tomcat
你的人类朋友7 小时前
快速搭建redis环境并使用redis客户端进行连接测试
前端·redis·后端
235168 小时前
【MySQL】数据库事务深度解析:从四大特性到隔离级别的实现逻辑
java·数据库·后端·mysql·java-ee
何中应9 小时前
MyBatis-Plus字段类型处理器使用
java·数据库·后端·mybatis
绝无仅有9 小时前
资深面试题之MySQL问题及解答(二)
后端·面试·github
绝无仅有9 小时前
某大厂库存秒杀的设计与实现总结
后端·面试·github
JavaPub-rodert10 小时前
用 go-commons 打造更优雅的字符串处理工具
开发语言·后端·golang
老华带你飞12 小时前
学生信息管理系统|基于Springboot的学生信息管理系统设计与实现(源码+数据库+文档)
java·数据库·spring boot·后端·论文·毕设·学生信息管理系统
Fency咖啡13 小时前
Spring 基础核心 - SpringMVC 入门与请求流程
java·后端·spring·mvc