[英]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.