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;
    }
}
相关推荐
新知图书16 小时前
搭建Spring Boot开发环境
java·spring boot·后端
宸津-代码粉碎机16 小时前
Spring Boot 4.0虚拟线程实战调优技巧,最大化发挥并发优势
java·人工智能·spring boot·后端·python
小码哥_常17 小时前
一个Starter搞定六种防护,Spring Boot API的超强护盾来了
后端
小村儿18 小时前
连载04-最重要的Skill---一起吃透 Claude Code,告别 AI coding 迷茫
前端·后端·ai编程
IT_陈寒19 小时前
Vite的alias配置把我整不会了,原来是这个坑
前端·人工智能·后端
gelald20 小时前
Spring Boot - 自动配置原理
java·spring boot·后端
希望永不加班20 小时前
SpringBoot 集成测试:@SpringBootTest 与 MockMvc
java·spring boot·后端·log4j·集成测试
uzong20 小时前
软件人员可以关注的 Skill,亲测确实不错,值得试一下
人工智能·后端
掘金虾20 小时前
Hono 框架入门到实战:用 Node.js 写一个支持工具调用的流式对话 Agent
后端
用户83562907805120 小时前
Python 自动拆分 Word 文档教程:按分节符与分页符处理
后端·python