1

我目前正在使用 Zendesk API 并创建用户。我正在使用 CompletableFuture 框架来执行创建用户的操作,然后添加一个回调来处理结果。但是,createUsers() 方法的结果是一个 JobStatus 对象,它的状态可能是“排队”、“完成”、“工作”。我想要的是只有在状态为“完成”时才执行回调。这可能吗?如果状态是“排队”,我希望它一直等到结果“完成”。

对于此示例,假设列表包含一组要创建的用户。

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

1 回答 1

0

如果您要使用代码:

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
}

睡眠操作肯定不理想,但通过 Zendesk API 只能检查作业状态完成状态。

于 2017-03-04T19:39:30.893 回答