[英]Only execute CompletableFuture callback when status of result is completed
我目前正在使用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
}
如果您将使用代码:
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,您只能检查作业状态完成状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.