Sub topic 14
When to use Quartz instead
This chapter assumes you know @Scheduled, cron expressions, the scheduler thread pool, and the multi-instance duplicate-execution problem from the earlier chapters. You should also be comfortable with Spring Boot configuration and basic JDBC setup.
@Scheduled is enough for many applications. It is small, needs no database, and lives next to the code it runs. This chapter covers where it stops being enough, what Quartz adds, and what Quartz costs.
What `@Scheduled` does not give you
Spring's scheduler keeps everything in memory. That has consequences:
- No persistence. If the process stops, the schedule's state is gone. Spring does not remember when a task last ran.
- No missed-run recovery. If the application is down at 02:00, the nightly job does not run when the application restarts. It waits for the next 02:00.
- No coordination between instances. Every instance runs every task. The multi-instance chapter described this duplicate-execution problem.
- No runtime changes. Schedules are fixed when the application starts. Changing one means a redeploy or a restart, unless you write your own
SchedulingConfigurerlogic. - No job history or per-job state. You cannot ask "when did job X last fire?" or attach data to a job across runs.
If you can live with these limits, stay with @Scheduled. If a requirement breaks one of them, consider Quartz.
What Quartz is
Quartz is a job-scheduling library for Java. It has been around much longer than Spring Boot and Spring supports it directly. Quartz separates three things that @Scheduled merges into one annotation:
| Quartz concept | Role | `@Scheduled` equivalent |
|---|---|---|
| `Job` | The code that runs | The annotated method |
| `JobDetail` | A named job with its class and a data map | None |
| `Trigger` | When the job fires (cron or simple interval) | `cron`, `fixedRate`, `fixedDelay` |
| `Scheduler` | Holds jobs and triggers, and runs them | The task scheduler bean |
| `JobStore` | Where jobs and triggers are kept (memory or database) | Always memory |
One job can have several triggers, and a trigger can be added, changed, paused, or removed while the application runs.
Deciding between the two
A distributed lock library such as ShedLock is the lighter fix for duplicate runs. It keeps your @Scheduled methods and adds a lock row in a shared store, so only the instance that acquires the lock runs the task. Choose Quartz when you also need persistence, missed-run handling, runtime management, or load spread across nodes.
Adding Quartz to Spring Boot
Add the starter. It brings in Quartz and auto-configures a Scheduler bean.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>Once the Quartz starter is on the classpath, Boot configures Quartz. Your @Scheduled methods still need @EnableScheduling and still run on Spring's own scheduler. The two systems coexist, and tasks in one are unaware of the other.
Writing a job
Extend QuartzJobBean and implement executeInternal. Boot creates job instances through Spring, so constructor injection works.
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
@DisallowConcurrentExecution
public class InvoiceJob extends QuartzJobBean {
private static final Logger log = LoggerFactory.getLogger(InvoiceJob.class);
private final InvoiceService invoiceService;
public InvoiceJob(InvoiceService invoiceService) {
this.invoiceService = invoiceService;
}
@Override
protected void executeInternal(JobExecutionContext context) {
log.info("Generating invoices, fired at {}", context.getFireTime());
invoiceService.generateMonthlyInvoices();
}
}@DisallowConcurrentExecution stops two runs of the same JobDetail from overlapping. With a clustered store this holds across nodes. With @Scheduled plus @Async you had to build that guard yourself.
Declaring the job and its trigger
Boot registers any JobDetail and Trigger beans with the scheduler.
import java.util.TimeZone;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QuartzConfig {
@Bean
public JobDetail invoiceJobDetail() {
return JobBuilder.newJob(InvoiceJob.class)
.withIdentity("invoiceJob")
.storeDurably()
.build();
}
@Bean
public Trigger invoiceTrigger(JobDetail invoiceJobDetail) {
return TriggerBuilder.newTrigger()
.forJob(invoiceJobDetail)
.withIdentity("invoiceTrigger")
.withSchedule(CronScheduleBuilder
.cronSchedule("0 0 2 * * ?")
.inTimeZone(TimeZone.getTimeZone("Europe/Berlin"))
.withMisfireHandlingInstructionFireAndProceed())
.build();
}
}storeDurably() keeps the job definition in the store even when no trigger points to it. That matters if you later add and remove triggers at runtime.
Differences in cron syntax
Quartz cron expressions are not identical to Spring's.
- Quartz has an optional seventh field, the year.
- In Quartz you must put
?in either the day-of-month or the day-of-week field. You cannot use*in both. Spring accepts*in both. - Day-of-week numbering and names differ in some versions. Use names such as
MON-FRIto avoid mistakes.
Persistence and clustering
The main reason to adopt Quartz is the JDBC job store. It writes jobs, triggers, and fire state to database tables. That gives you survival across restarts and a way to coordinate several instances through row locks.
spring:
quartz:
job-store-type: jdbc
jdbc:
initialize-schema: always
properties:
org.quartz.scheduler.instanceId: AUTO
org.quartz.jobStore.isClustered: true
org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
org.quartz.threadPool.threadCount: 8What each setting does:
job-store-type: jdbcswitches from the in-memory store to the database configured as your SpringDataSource.initialize-schema: alwayscreates the Quartz tables (they start withQRTZ_) at startup. In production, prefer creating them with your migration tool (Flyway or Liquibase) and set this tonever.instanceId: AUTOgives each node a unique ID.isClustered: truemakes the nodes cooperate. For each trigger firing, one node acquires it through a database lock, and the others skip it.driverDelegateClasstells Quartz the SQL dialect. Use the delegate that matches your database.threadCountsets the size of Quartz's own worker pool. It is separate fromspring.task.scheduling.pool.size.
With clustering, a trigger that fires once is executed once across the cluster, and different jobs can run on different nodes. That spreads load, which a lock-based approach does not do.
Misfires
A misfire happens when a trigger should have fired but could not, for example because all worker threads were busy or the application was down. Quartz decides what to do from the trigger's misfire instruction. For cron triggers, the common choices are:
| Instruction | Behavior |
|---|---|
| `withMisfireHandlingInstructionFireAndProceed` | Fire once right away, then continue on the normal schedule |
| `withMisfireHandlingInstructionDoNothing` | Skip the missed run and wait for the next one |
| `withMisfireHandlingInstructionIgnoreMisfires` | Fire every missed run as fast as possible |
Pick this on purpose. A report that must exist every morning wants fire-and-proceed. A cache refresh that is stale anyway wants do-nothing. The last option can cause a burst after a long outage.
Changing schedules at runtime
Inject the Scheduler and reschedule without a restart.
import org.quartz.CronScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.stereotype.Service;
@Service
public class ScheduleAdmin {
private final Scheduler scheduler;
public ScheduleAdmin(Scheduler scheduler) {
this.scheduler = scheduler;
}
public void changeInvoiceCron(String cron) throws SchedulerException {
TriggerKey key = TriggerKey.triggerKey("invoiceTrigger");
Trigger old = scheduler.getTrigger(key);
Trigger replacement = old.getTriggerBuilder()
.withSchedule(CronScheduleBuilder.cronSchedule(cron))
.build();
scheduler.rescheduleJob(key, replacement);
}
}scheduler.pauseJob, resumeJob, deleteJob, and triggerJob (fire once now) cover the other common admin actions. This is what makes Quartz fit applications where users or operators define schedules.
Costs of switching
Quartz is more machinery than @Scheduled, so weigh these costs:
- Database dependency. The scheduler needs the database to be reachable. If it is down, no jobs fire.
- More schema and upgrades. You maintain the
QRTZ_tables and must keep them compatible when you upgrade Quartz. - Clock sensitivity. Clustered nodes should have synchronized clocks. Large drift causes odd firing and false node-failure detection.
- Serialization. Job data in the store is serialized. Keep
JobDataMapvalues simple (strings, numbers), not Spring beans. - Testing. Jobs are classes with a
JobExecutionContext. Keep logic in a service, asInvoiceJobdoes, so you can unit-test the service without Quartz. - Two thread pools. Quartz workers do not use
spring.task.scheduling. Size and monitor them separately.
Common errors
- Job never fires. The
Triggerbean has noforJob(...)link, or theJobDetailis not durable and has no trigger. NoSuchBeanDefinitionExceptioninside a job. The job was created outside Spring, for instance through a hand-builtJobFactory. Use the Boot auto-configuration, or setSpringBeanJobFactoryyourself.- Duplicate runs in a cluster.
isClusteredisfalse, or nodes use separate databases, orinstanceIdis the same on every node. - Schema errors on startup. The tables do not exist and
initialize-schemaisnever, or thedriverDelegateClassdoes not match the database. - Changed cron in code has no effect. With a JDBC store, the stored trigger wins over a bean definition that already exists. Reschedule through the
Scheduler, or delete the old trigger.
Exercise
A service runs on four instances. A nightly job must run exactly once per night, even if all instances restart at 01:55. It must also run at the next startup if the whole system was down at 02:00. Which tool fits, and which two settings make it work?
Show answer
Quartz with the JDBC job store. Set spring.quartz.job-store-type: jdbc so triggers and fire times are persisted, which lets the job be recognized as missed after downtime. Set org.quartz.jobStore.isClustered: true (with instanceId: AUTO) so only one node fires each trigger. Give the cron trigger a fire-and-proceed misfire instruction so a missed 02:00 run executes once at the next startup. ShedLock alone would stop duplicates but would not run the missed job.