简体   繁体   中英

Only execute CompletableFuture callback when status of result is completed

I am currently working with the Zendesk API and creating users. I am using the CompletableFuture framework to perform the operation of creating the users and then adding a callback to handle the result. However, the result of the createUsers() method is a JobStatus object that could have the status of "queued", "completed", "working". What I would like is for the callback to be executed only when the status is "completed". Is this possible? If the status is "queued", I want it to keep waiting until the result is "completed".

For this example, assume that the list contains a set of users to be created.

public void createEndUsers(Zendesk zd, List<User> usersToBeCreated){
    final static CompletableFuture<JobStatus<User>> promise = new CompletableFuture<>();

    promise.supplyAsync(() -> {
            JobStatus<User> js = zd.createUsers(usersToBeCreated);
            return js;
        }).thenAccept(Testing::updateDB);
}

public void updateDB(JobStatus<User> resultObject){
    //perform various operations on the JobStatus object
}

If you would be using the code:

private static final int DELAY = 100;
public void createEndUsers(Zendesk zd, List<User> usersToBeCreated){
    final CompletableFuture<JobStatus<User>> promise = new CompletableFuture<>();

    promise.supplyAsync(() -> {
        JobStatus<User> js = zd.createUsers(usersToBeCreated);
        JobStatus.JobStatusEnum jsStatus = js.getStatus();

        while (jsStatus == JobStatus.JobStatusEnum.working || jsStatus == JobStatus.JobStatusEnum.queued){
            try{
                Thread.sleep(DELAY);
            } catch(InterruptedException e){
                throw new RuntimeException("Interrupted exception occurred while sleeping until the next attempt of retrieving the job status for the job " + js.getId(), e);
            }
            js =  zd.getJobStatus(js);
            jsStatus =js.getStatus();
        }
        return js;
    }).thenAccept(Testing::updateDB);
}

public static void updateDB(JobStatus<User> resultObject){
    //perform various operations on the JobStatus object
}

The sleeping operation is definitely not ideal, but via Zendesk API you can only check for the job status completion status.

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.

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