2017-03-01 103 views
0

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

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

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 
} 
+0

如果您没有CompletableFuture,您会怎么做?这里没有魔法,你需要轮询JobStatus的状态,或者createUsers应该被重写为不返回中间对象。 – john16384

+0

createUsers不能被重写,因为它是Zendesk API的一部分,我不想干涉它。至于其他方面,我可以简单地做一个循环来检查Zendesk API并更新JobStatus对象的状态,并在状态“完成”之前一直这样做,但我希望有一种更优雅的方式在某些条件下回调。 – Kristianasp

+0

有一个创建单个用户的API调用。它似乎只在工作完成时才会返回。看起来你可以直接调用其中的多个,直到你创建它们全部为止。 – 2017-07-13 02:59:25

回答

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,你可以只检查作业状态完成状态。

相关问题