I am trying to implement a polling functionality which does this:
while (condition is false or it does not timeout):
call another end point
wait(x seconds)
I wrote below code:
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;
}
But it's not correct implementation as the process still remains active even after execution and also it does not look syntactically correct. Anybody know what I am doing wrong here?
I think you probably need to update the status, like this:
int currentStatus = fetchStatus();
System.out.println("current c: " + currentStatus);
if (isStatusFinal(currentStatus)) {
completionFuture.complete(currentStatus);
} else {
//update status
}
or do the update status thing at some otherwhere.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.