I have a scheduler application which runs using Spring Boot & Quartz. I have created the job with multiple triggers (cron) which is running perfectly fine. The details of the job, cron expressions are storing at the database.
Here is the requirement, whenever restarting the application the stored triggers are not firing. I know a workaround to make it happen. Storing the details of job, trigger in a user defined table. Should be loaded upfront whenever the application starts. But I am not sure the approach is right or wrong.
Also I have referred lot of articles and github projects to find out how to restart/resume/re-initiate jobs.
There could be a solution where I couldn't find, maybe lack of understanding of quartz or something. I am sure someone would have experienced the scenario and found a way to overcome it. It will be grateful if someone provide an answer.
You can get the scheduled-jobs from the database and on application startup using ApplicationRunner or using @EventListener(ApplicationReadyEvent.class) and call to 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);
}
}
}
OR
@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);
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With