异步处理任务,失败延迟重试

发布时间 2023-07-21 15:16:53作者: 咖啡来一杯

for循环 失败处理后,延迟重试

// for循环 失败处理后,延迟重试
@Test
void test28() throws InterruptedException {

    ExecutorService executorService = Executors.newFixedThreadPool(3);
    executorService.execute(() -> {

        // 最大重试次数
        int maxTryCount = 3;
        // 最大重试时间(秒)
        int maxWaitTime = 1;
        for (int tryCount = 0; tryCount < maxTryCount; tryCount++) {
            try {

                // log.info("处理任务:" + (tryCount + 1));
                int a = 1 / 0;

                break;
            } catch (Exception e) {
                log.error("处理任务失败,原因是:{}", e.toString());
                if (tryCount == maxTryCount - 1) {
                    // 1.记录日志
                    log.error("超过最大尝试次数,记录日志:{}", e.toString());
                    // 2.发送邮件
                }

                // 延迟重试
                try {
                    TimeUnit.SECONDS.sleep(maxWaitTime);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }

            }
        }

    });

    TimeUnit.SECONDS.sleep(5);

}

// while循环 失败处理后,延迟重试
@Test
void test29() throws InterruptedException {

    InheritableThreadLocal<String> data = new InheritableThreadLocal<>();
    data.set("李四");

    ExecutorService executorService = Executors.newFixedThreadPool(3);

    executorService.execute(() -> {

        int tryCount = 0;
        int maxTryCount = 3;

        while (tryCount < maxTryCount) {
            try {
                log.info("执行任务");
                int a = 1 / 0;
                break;
            } catch (Exception e) {
                log.error("处理任务失败,原因是:{}", e.toString());
                tryCount++;

                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }

                if (tryCount == maxTryCount) {
                    // 1.记录日志
                    log.error("超过最大尝试次数,记录日志:{}", e.toString());
                    // 2.发送邮件
                }
            }

        }

    });

    TimeUnit.SECONDS.sleep(5);

}