简体   繁体   English

仅在结果状态完成时才执行CompletableFuture回调

[英]Only execute CompletableFuture callback when status of result is completed

I am currently working with the Zendesk API and creating users. 我目前正在使用Zendesk API并正在创建用户。 I am using the CompletableFuture framework to perform the operation of creating the users and then adding a callback to handle the result. 我正在使用CompletableFuture框架执行创建用户的操作,然后添加回调以处理结果。 However, the result of the createUsers() method is a JobStatus object that could have the status of "queued", "completed", "working". 但是,createUsers()方法的结果是一个JobStatus对象,其状态可能为“已排队”,“已完成”,“正在工作”。 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. 休眠操作绝对不理想,但是通过Zendesk API,您只能检查作业状态完成状态。

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

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