[英]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.