2

我想在一段时间内失败时重试我的函数调用。最好的方法是什么。这会正常工作吗。

CompletableFuture.runAsync(() -> {
    for (int i = 0; i < 3; i++) {
        try {
            dndService.initateDNDRequest(transactionId, circle, category, "PREPAID");       
            break;
        } catch (Exception e) {
            try {
                TimeUnit.SECONDS.sleep(10);//wait for few minutes while next attempt
            } catch (InterruptedException e1) {
                LOGGER.error("Error while retrying request for DND.");
            }
            LOGGER.error("Request retry for DND count"+i);
        }
    }
}, executor);
4

1 回答 1

5

您不应该将执行程序的工作线程放到sleep.

安排新尝试的一种解决方案是

    Executor executor; // … the actual executor
    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    Executor afterTenSeconds
        = r -> ses.schedule(() -> executor.execute(r), 10, TimeUnit.SECONDS);

    Runnable primaryAction
        = () -> dndService.initateDNDRequest(transactionId, circle, category, "PREPAID");

    CompletableFuture<Void> cf = CompletableFuture.runAsync(primaryAction, executor);
    for(int i = 0; i < 3; i++) {
        cf = cf.handle((v,t) -> t == null? CompletableFuture.completedFuture(v):
                                CompletableFuture.runAsync(primaryAction, afterTenSeconds))
               .thenCompose(Function.identity());
    }

然后handle动作将安排一个新的尝试,在失败情况下超时(十秒)后执行。这thenCompose(Function.identity())是必要的,因为没有单一的方法来组合handlecompose语义。

请注意,从 Java 9 开始,您可以像这样简单地创建延迟执行器

Executor afterTenSeconds = CompletableFuture.delayedExecutor(10,TimeUnit.SECONDS,executor);

无需处理ScheduledExecutorService自己。

于 2018-06-04T17:46:02.597 回答