2011-10-15 209 views
1

我有2個任務 - 任務A和任務B.任務A應該首先執行,完成後,我要啓動我的週期性任務B,該任務繼續執行任務直至成功。 如何在java中實現這個功能?我正在考慮計劃執行服務,但這些服務似乎更多基於時間而不是任務狀態。Java:計劃任務

回答

1

這裏有一種方法:

import java.util.concurrent.*; 

public class ScheduledTasks { 
    public static void main(String[] args) { 
     ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3); 
     FollowupTask followupTask = new FollowupTask(executorService); 
     FirstTask firstTask = new FirstTask(followupTask, executorService); 
     executorService.submit(firstTask); 
    } 

    static class FirstTask implements Runnable { 
     private FollowupTask followup; 
     private ScheduledExecutorService executorService; 

     FirstTask(FollowupTask followup, ScheduledExecutorService executorService) { 
      this.followup = followup; 
      this.executorService = executorService; 
     } 

     @Override 
     public void run() { 
      System.out.println("First task: counting to 5"); 
      for (int i = 1; i <= 5; i++) { 
       sleep(1000); 
       System.out.println(i); 
      } 
      System.out.println("All done! Submitting followup task."); 
      executorService.submit(followup); 
     } 
    } 

    static class FollowupTask implements Runnable { 
     private int invocationCount = 0; 
     private ScheduledExecutorService executorService; 

     public FollowupTask(ScheduledExecutorService executorService) { 
      this.executorService = executorService; 
     } 

     @Override 
     public void run() { 
      invocationCount++; 
      if (invocationCount == 1) { 
       System.out.println("Followup task: resubmit while invocationCount < 20"); 
      } 
      System.out.println("invocationCount = " + invocationCount); 
      if (invocationCount < 20) { 
       executorService.schedule(this, 250, TimeUnit.MILLISECONDS); 
      } else { 
       executorService.shutdown(); 
      } 
     } 
    } 

    static void sleep(long millis) { 
     try { 
      Thread.sleep(millis); 
     } catch (InterruptedException e) { 
      throw new IllegalStateException("I shouldn't be interrupted!", e); 
     } 
    } 
}