Вы можете получить запланированные задания из базы данных и при запуске приложения, используя ApplicationRunner
или @EventListener(ApplicationReadyEvent.class)
и вызывая startAllSchedulers()
.
public class SchedulerStartUpHandler implements ApplicationRunner {
@Autowired
private SchedulerService schedulerService;
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("Schedule all new scheduler jobs at app startup - starting");
try {
schedulerService.startAllSchedulers();
log.info("Schedule all new scheduler jobs at app startup - complete");
} catch (Exception ex) {
log.error("Schedule all new scheduler jobs at app startup - error", ex);
}
}
}
ИЛИ
@EventListener(ApplicationReadyEvent.class)
public void startTheScheduledJobFromDatabase() {
startAllSchedulers();
}
startAllSchedulers ()
public void startAllSchedulers() {
List<SchedulerJobInfo> jobInfoList = schedulerRepository.findAll();
if (jobInfoList != null) {
Scheduler scheduler = schedulerFactoryBean.getScheduler();
jobInfoList.forEach(jobInfo -> {
try {
JobDetail jobDetail = JobBuilder.newJob(SampleCronJob.class)
.withIdentity(jobInfo.getJobName(), jobInfo.getJobGroup()).build();
if (!scheduler.checkExists(jobDetail.getKey())) {
Trigger trigger;
jobDetail = scheduleCreator.createJob(SampleCronJob.class,
false, context, jobInfo.getJobName(), jobInfo.getJobGroup());
if (jobInfo.getCronJob() && CronExpression.isValidExpression(jobInfo.getCronExpression())) {
trigger = scheduleCreator.createCronTrigger(jobInfo.getJobName(), new Date(),
jobInfo.getCronExpression(), SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
} else {
trigger = scheduleCreator.createSimpleTrigger(jobInfo.getJobName(), new Date(),
jobInfo.getRepeatTime(), SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
}
scheduler.scheduleJob(jobDetail, trigger);
}
} catch (SchedulerException e) {
log.error(e.getMessage(), e);
}
});
}
}