Skip to main content

Quartz

Dynamic Quartz Job Scheduling in Spring Boot
·4 mins read
Mayukh Datta
Technical Quartz Spring Boot
Quartz is a feature-rich open-source Java library used to schedule jobs. The core components of this library are Job, JobDetail, Trigger, and Scheduler. The JobDetail is where the job definition lies. The Trigger contains the instructions about when the job should get executed and Scheduler who runs the Job. Spring Boot Maven Dependency for Quartz library # <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> The Core Components # Job: We create our own jobs by extending the QuartzJobBean class that implements Job interface. This interface has one method execute(JobExecutionContext context), which is overriden by the QuartzJobBean. This is where the scheduled task runs and the information on the JobDetail and Trigger is retrieved using the JobExecutionContext. The QuartzJobBean also gives us an abstract method executeInternal(JobExecutionContext context). Your Job class needs to override the executeInternal(...) method and should contain the code you want to get processed when the job gets executed. public class MyJob extends QuartzJobBean { ... @Override protected void executeInternal(@NonNull JobExecutionContext context) { ... } } JobDetail: Defining the Job. JobDetail jobDetail = JobBuilder.newJob(MyJob.class) .withIdentity(jobName) .storeDurably() .requestRecovery() .usingJobData(jobDataMap) .build(); Trigger: Defining the schedule upon which the job will be executed. Trigger jobTrigger = TriggerBuilder.newTrigger() .forJob(jobDetail) .startAt(scheduledAt) .withIdentity(triggerName) .build(); Scheduler: This is the main API for interacting with the Quartz Scheduler. We can get an instance of the Scheduler from the SchedulerFactoryBean. public class MyJob extends QuartzJobBean { @Autowired SchedulerFactoryBean schedulerFactoryBean; ... public void start(...) { Scheduler timer = schedulerFactoryBean.getScheduler(); timer.start(); ... timer.scheduleJob(jobDetail, jobTrigger); } Job Persistence # Quartz gives us JobStore for storing all the Job, Trigger and Scheduler related data.