2011-10-15 53 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); 
     } 
    } 
}