[英]Scheduling: execute tasks only one time in spring boot
我試圖使用spring boot管理計划任務。 我想在特定日期 (由用戶指定)執行我的工作一次 。 用戶可以根據需要添加執行日期。這是我的工作:
@Component
public class JobScheduler{
@Autowired
ServiceLayer service;
@PostConstruct
public void executeJob(){
try {
service.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
這是執行方法:
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:我正在使用PostConstruct注釋。 因此,當調用executeJob方法時,列表'myListOfDates'中沒有日期。
問題2:假設myListOfDates包含日期,如果用戶輸入另一個日期,我如何獲得最新日期?
問題3:如果我使用@Scheduled(initailDelay = 10000,fixedRate = 20000)而不是@PostConstruct注釋,它將解決第一個問題,但它將每隔20秒執行一次我的工作。
任何線索?
從我的問題可以推斷出,你問的是如何根據春天開始時的一些日期列表觸發工作。
首先 ,我認為最好將它掛鈎到應用程序級事件偵聽器中,而不是在bean /組件中使用@PostConstruct
。 請參閱http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/event/ContextRefreshedEvent.html
這樣,您可以確保所有bean都已初始化,因此您可以加載myListOfDates
,然后啟動調度程序。
其次 ,就像我在評論中所說的那樣,我建議您使用現有的第三方庫。 我只在java中使用Quartz,所以我將使用Quartz進行說明。
第三 ,我猜你將myListOfDates
存儲在某種數據庫(而不是內存)中,因此用戶可以修改預定日期。 如果您按照我的建議使用第三方庫,Quartz使用JDBC的JobStore請參閱http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/tutorial-lesson-09.html#TutorialLesson9- JDBCJobStore
老實說,我從來沒有使用過那個,但我相信圖書館有根據數據庫中保存的內容觸發工作的機制。 這可能就是你要找的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.