How to use ExecutorService to poll until a result arrives

前端 未结 2 1261
情话喂你
情话喂你 2021-02-04 12:31

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

2条回答
  •  终归单人心
    2021-02-04 12:36

    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;
    }
    

提交回复
热议问题