Sub topic 14
When to use Quartz instead
This chapter assumes you know @Scheduled, the scheduler thread pool, and why several application instances can run the same task twice. Here you decide when @Scheduled stops being enough and what Quartz adds.
What @Scheduled does not give you
@Scheduled tasks are defined at compile time and live in memory. That leads to four limits:
- The schedule is fixed in code or configuration. Changing it means a restart.
- Nothing is persisted. If the application is down at 02:00, the nightly run is simply skipped.
- Every instance runs every task. Nothing coordinates instances.
- You cannot ask the scheduler which jobs exist, pause one, or trigger one on demand.
Quartz is a job scheduling library that addresses these limits. It is not a replacement for every @Scheduled method.
How Quartz is structured
Quartz separates three things:
| Concept | Role |
|---|---|
| `Job` | The code to run. |
| `JobDetail` | A description of a job, with a name, group, and data map. |
| `Trigger` | When to run it. A job can have several triggers. |
With a JDBC job store, Quartz saves jobs and triggers in database tables. It uses row locks in that database so only one instance fires a given trigger. That is the main reason teams adopt it.
Adding Quartz to Spring Boot
Add spring-boot-starter-quartz and a database driver. Then configure the JDBC store:
spring:
quartz:
job-store-type: jdbc
jdbc:
initialize-schema: always
properties:
org.quartz.jobStore.isClustered: true
org.quartz.scheduler.instanceId: AUTOinitialize-schema: always creates the tables at startup. In production, prefer never and manage the schema with your migration tool.
A job extends QuartzJobBean, and you declare it with a JobDetail and a Trigger:
import org.quartz.*;
import org.springframework.context.annotation.*;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class ReportJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) {
System.out.println("generating report");
}
}
@Configuration
class QuartzConfig {
@Bean
JobDetail reportJobDetail() {
return JobBuilder.newJob(ReportJob.class)
.withIdentity("reportJob")
.storeDurably()
.build();
}
@Bean
Trigger reportTrigger(JobDetail reportJobDetail) {
return TriggerBuilder.newTrigger()
.forJob(reportJobDetail)
.withIdentity("reportTrigger")
.withSchedule(CronScheduleBuilder
.cronSchedule("0 0 2 * * ?"))
.build();
}
}Note that Quartz cron expressions differ from Spring's. They use ? for "no specific value" in the day-of-month or day-of-week field, and they allow an optional year field.
Misfires
A misfire happens when a trigger could not fire on time, for example because the application was down or all worker threads were busy. Each trigger has a misfire instruction that says what to do: fire once now, skip to the next scheduled time, and so on. @Scheduled has no equivalent. It simply runs the next occurrence.
Decision criteria
| Need | Choice |
|---|---|
| A simple periodic task on one instance | `@Scheduled` |
| Multiple instances, but a duplicate run is harmless | `@Scheduled` |
| Exactly one instance should run each trigger | Quartz clustered, or a lock library such as ShedLock with `@Scheduled` |
| Schedules created or changed at runtime | Quartz |
| Missed runs must be recovered | Quartz |
| Pause, resume, or trigger jobs by name | Quartz |
Exercise
A service runs on three instances and sends a daily digest email. The schedule is fixed and a missed run is acceptable, but users must not receive three emails. Do you need Quartz? Explain.
Show answer
Not necessarily. The requirement is one execution per trigger, and nothing needs persistence, runtime changes, or misfire recovery. Keeping @Scheduled and adding a distributed lock such as ShedLock is simpler. Quartz clustered mode would also work, but it adds database tables and a separate scheduler to operate.
Exercise
Name two features Quartz offers that @Scheduled does not.
Show answer
Any two of: persistent jobs and triggers in a database, clustered coordination so one instance fires each trigger, misfire handling, and creating, pausing, or rescheduling jobs at runtime.