I have a scenario where I have to poll a remote server checking if a task has completed. Once it has, I make a different call to retrieve the result.
I originally figure
I think CompletableFutures are a fine way to do this:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private void run() {
final Object jobResult = pollForCompletion("jobId1")
.thenApply(jobId -> remoteServer.getJobResult(jobId))
.get();
}
private CompletableFuture pollForCompletion(String jobId) {
CompletableFuture completionFuture = new CompletableFuture<>();
final ScheduledFuture checkFuture = executor.scheduleAtFixedRate(() -> {
if (remoteServer.isJobDone(jobId)) {
completionFuture.complete(jobId);
}
}, 0, 10, TimeUnit.SECONDS);
completionFuture.whenComplete((result, thrown) -> {
checkFuture.cancel(true);
});
return completionFuture;
}