繁体   English   中英

无法使用 ScheduledExecutorService 实现异步轮询

[英]Unable to implement asynchronous polling using ScheduledExecutorService

我正在尝试实现执行此操作的轮询功能:

while (condition is false or it does not timeout):
   call another end point
   wait(x seconds)

我写了下面的代码:

private static CompletableFuture<Integer> asyncStatusChecker() {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    CompletableFuture<Integer> completionFuture = new CompletableFuture<>();
    final ScheduledFuture<?> checkFuture = executor.scheduleAtFixedRate(() -> {
        int currentStatus = fetchStatus();
        System.out.println("current c: " + currentStatus);
        if (isStatusFinal(currentStatus)) {
            completionFuture.complete(currentStatus);
        }
    }, 5, 1, TimeUnit.SECONDS);
    completionFuture.whenComplete((result, thrown) ->
            checkFuture.cancel(true));
    completionFuture.orTimeout(10, TimeUnit.SECONDS);
    return completionFuture;
}

但这不是正确的实现,因为即使在执行之后进程仍然保持活动状态,而且它看起来在语法上也不正确。 有人知道我在这里做错了什么吗?

我认为您可能需要更新状态,如下所示:

    int currentStatus = fetchStatus();
    System.out.println("current c: " + currentStatus);
    if (isStatusFinal(currentStatus)) {
        completionFuture.complete(currentStatus);
    } else {
        //update status
    }

或者在其他地方做更新状态的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM