SpringBoot编码技巧-ScheduledExecutorService轮询

摘要:本文主要介绍在Springboot环境中,启动的时候或者我们功能依赖于其他的服务,我们需要等待其他服务完成后才能执行我们的代码,这里提供一个更好的案例,便于大家在代码中使用。

WaitService

平常的时候,我们用的最多的就是while Thread.sleep来使用,这里用ScheduledExecutorService来判断,更优雅一点

java 复制代码
public class WaitService {

    public Result packageApk(){
        Result result = new Result();
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                ThreadFactoryBuilder.create().setNamePrefix("schedule-pool-package-apk-").setDaemon(true).build());
        try {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            Runnable runnable = () -> {
                // 判断其他依赖项是否已经启动完成,这里用随机数1成功,0失败,其他表示还在等待
                Random random = new Random();
                int i = random.nextInt(10);
                System.out.println("当前随机数:"+ i);
                if(i == 1){
                    result.setSuccess(true);
                    countDownLatch.countDown();
                }else if(i == 0){
                    result.setSuccess(false);
                    countDownLatch.countDown();
                }
            };
            executorService.scheduleAtFixedRate(runnable, 5, 5, TimeUnit.SECONDS);
            countDownLatch.await(5, TimeUnit.MINUTES);
        } catch (Exception ex) {
            result.setSuccess(false);
            result.setMessage(ex.getMessage());
            ex.printStackTrace();
        } finally {
            if(!executorService.isShutdown()){
                executorService.shutdown();
            }
        }
        return result;
    }

    @Data
    public static class Result {

        private Boolean success;

        private String message;

    }

    public static void main(String[] args) {
        WaitService waitService = new WaitService();
        Result result = waitService.packageApk();
        System.out.println("success="+result.getSuccess()+", message=" + result.getMessage());
    }

}

结果

csharp 复制代码
Connected to the target VM, address: '127.0.0.1:61037', transport: 'socket'
当前随机数:6
当前随机数:5
当前随机数:2
当前随机数:9
当前随机数:7
当前随机数:9
当前随机数:9
当前随机数:4
当前随机数:7
当前随机数:2
当前随机数:2
当前随机数:1
success=true, message=null
相关推荐
Olrookie20 分钟前
若依前后端分离版学习笔记(二十)——实现滑块验证码(vue3)
java·前端·笔记·后端·学习·vue·ruoyi
LucianaiB36 分钟前
招聘可以AI面试,那么我制作了一个AI面试教练不过分吧
后端
倚栏听风雨1 小时前
java.lang.SecurityException异常
java
星河队长1 小时前
VS创建C++动态库和C#访问过程
java·c++·c#
无奈何杨1 小时前
CoolGuard更新,ip2region升级、名单增加过期时间
后端
鼠鼠我捏,要死了捏2 小时前
Java虚拟线程原理与性能优化实战
java·performance-optimization·virtual-thread
艾菜籽2 小时前
Spring MVC练习:留言板
java·spring·mvc
摇滚侠2 小时前
Spring Boot 3零基础教程,WEB 开发 自定义静态资源目录 笔记31
spring boot·笔记·后端·spring
摇滚侠2 小时前
Spring Boot 3零基础教程,WEB 开发 Thymeleaf 遍历 笔记40
spring boot·笔记·thymeleaf
Anthony_49262 小时前
逻辑清晰地梳理Golang Context
后端·go