2016-05-29 104 views
2

我試圖使用彈簧啓動管理計劃任務。我想在特定日期(由用戶指定)只執行一次我的工作。用戶可以執行儘可能多的加入紅棗,因爲他wants.Here是我的工作:調度:在春季啓動時僅執行一次任務

@Component 
public class JobScheduler{ 

    @Autowired 
    ServiceLayer service; 

    @PostConstruct 
    public void executeJob(){ 
     try { 
      service.execute(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 
} 

這裏是執行法:用PostConstruct註釋林:

private TaskScheduler scheduler; 

Runnable exampleRunnable = new Runnable(){ 
    @Override 
    public void run() { 
     System.out.println("do something ..."); 
    } 
}; 

@Override 
    @Async 
    public void execute() throws Exception { 
     try { 

      List<Date> myListOfDates = getExecutionTime(); // call dao to get dates insered by the user 

      ScheduledExecutorService localExecutor = Executors.newSingleThreadScheduledExecutor(); 
      scheduler = new ConcurrentTaskScheduler(localExecutor); 
      for(Date d : myListOfDates){ 
      scheduler.schedule(exampleRunnable, d); 
      } 

     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

第1期。因此,當調用executeJob方法時,List'myListOfDates'中沒有日期。

問題2:假設myListOfDates包含日期,如何在用戶輸入另一個日期的情況下獲取最新日期?

問題3:如果我使用@Scheduled(ini​​tailDelay = 10000,fixedRate = 20000)而不是@PostConstruct註釋,它將解決第一個問題,但它會每隔20秒執行一次我的工作。

任何線索?

+0

我想你最好使用第三方庫進行排程,比如石英。這些都經過充分測試,生產就緒,並且易於配置。 – dieend

+0

我認爲石英包括兩種類型的觸發器:SimpleTrigger - 允許設置開始時間,結束時間,重複間隔。 CronTrigger - 允許Unix cron表達式指定運行作業的日期和時間。沒有一個適合我的問題。我錯了嗎 ? – Daniel

+0

'SimpleTrigger應該滿足您的日程安排需求,如果您需要在特定時刻及時執行一次作業或在特定時間執行一次,然後在特定時間間隔重複執行......重複次數可以爲零。 ..' http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/tutorial-lesson-05.html它是否符合您的需求? – dieend

回答

2

從我的問題可以推斷出,你問的是如何在春季開始時根據一些日期列表觸發作業。

第一個,而不是在一個bean /組件中使用@PostConstruct,我認爲最好是將它掛接到應用程序級事件偵聽器中。請參閱http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/event/ContextRefreshedEvent.html

這樣,您可以確保所有的bean都已初始化,因此您可以加載myListOfDates,然後啓動調度程序。

第二個,就像我在我的評論中所說的,我建議你使用現有的第三方庫代替。我只使用Java中的Quartz,因此我將使用Quartz進行ilustrate。

第三,我想你在myListOfDates存儲某種數據庫(而不是內存),因此用戶修改預定日期的能力。如果你遵循我的建議使用第三方庫,Quartz有使用JDBC的JobStore請參閱http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/tutorial-lesson-09.html#TutorialLesson9-JDBCJobStore

老實說,我從來沒有使用過那個,但我相信庫有機制來根據保存在數據庫中的內容觸發作業。這可能是你正在尋找的。

+1

我做了它的工作感謝第三個技巧:使用JDBC的JobStore。 – Daniel