The smallmind-schedule module is a thin, opinionated adaptation of
Quartz for services that already run inside
a Spring application context. It does not rewrite Quartz. It does not hide it.
It provides the small, repeatable piece of plumbing that every Quartz-on-Spring
integration ends up hand-writing: a Quartz Job base class that records how
long it ran and what it produced, a JobFactory that resolves job beans from
the Spring context, a SchedulerFactory that ties scheduler lifecycle to
context lifecycle, a pair of InitializingBean implementations that install
and retire CronTrigger schedules declaratively, and a JMX facade for
operators who need to pause triggers without redeploying.
It is organized as two independently publishable artifacts:
-
schedule-base— a framework-neutral contract (ProxyJob) and nothing else. No Quartz dependency, no Spring dependency. Safe to import from a service interface module, a shared model jar, or any library that wants to describe a schedulable unit of work without pulling in the runtime that executes it. -
schedule-quartz— the Quartz implementation. ImplementsProxyJobas an abstractInterruptableJobbase class, wires a QuartzSchedulerinto a SpringApplicationContext, installs and retires cron schedules from bean definitions, and exposes scheduler lifecycle over JMX. Ships a ready-to-import Spring XML configuration and the Liquibase changelog that references theQRTZ_*metadata tables.
The module is small by design: one interface in schedule-base, eleven classes
plus three Spring XML files and a Liquibase changelog reference in
schedule-quartz. It exists to turn Quartz into something a Spring service
can adopt in an afternoon — without learning the Quartz bean graph, without
writing a JobFactory for Spring integration, without hand-coding trigger
installation logic that has to decide between "add" and "replace," and without
coupling the service’s public API to Quartz.
Quartz is a capable scheduler with a long track record, but it has a shape problem for services whose scheduling work is a minor part of a larger application. A production Quartz-on-Spring setup needs, at minimum:
-
A
SchedulerFactory— typically the JDBC-backedStdSchedulerFactory— configured from aPropertiesinstance with twenty-plus entries covering the instance name, thread pool, job store, datasource, clustering, and RMI exposure. -
A bridge between Spring and Quartz job instantiation. Out of the box, Quartz instantiates
Jobclasses viaClass.newInstance(); a Spring service wants dependency-injected@Autowiredfields and prototype-scoped beans, which requires a customorg.quartz.spi.JobFactory. -
Lifecycle coordination. The Quartz scheduler is started, paused, and shut down explicitly. A Spring service wants the scheduler to come up when the context is ready and shut down cleanly — waiting for in-flight jobs — when the context closes.
-
Declarative schedule management. Every Quartz job is a
JobDetailpaired with one or moreTriggerinstances, keyed bynameandgroup. A service wants to declare "these jobs on these cron expressions" in a configuration file, have missing jobs added, changed jobs replaced, and obsolete jobs deleted — all at startup, without bespoke bootstrap code. -
Bookkeeping that survives a crash. Every job firing produces a start time, a stop time, an outcome (success / failure / interrupted), a processed count, and zero or more exceptions. A service wants that information in its log stream, formatted consistently, without every job author reimplementing it.
-
An operator control surface. At 03:00 in production, an on-call engineer may need to suspend trigger firing without redeploying the service. A service wants that control exposed through an existing operational channel — JMX — rather than through a new one.
-
A database schema. The
JobStoreTXjob store requires theQRTZ_*metadata tables. A service wants those created and migrated as part of the same startup that initializes the scheduler.
smallmind-schedule assembles all seven, once, as an importable Spring XML
file plus a handful of collaborating beans, and exposes one abstract
QuartzProxyJob class that subclasses implement in terms of proceed() and
cleanup() — nothing else.
-
Defines a neutral job contract (
ProxyJobinschedule-base) so shared libraries can describe a schedulable unit of work without referencing Quartz. -
Implements
ProxyJobover Quartz’sInterruptableJob(QuartzProxyJob), recording start and stop timestamps, tracking a processed-item count, accumulating exceptions, and emitting a single structured log entry at the end of each firing. -
Resolves job instances from a Spring context (
SpringJobFactory), enforcing that every job bean is prototype-scoped so each firing gets a fresh instance with freshly injected collaborators. -
Ties scheduler lifecycle to Spring context lifecycle (
SpringSchedulerFactory), exposing anactiveModetoggle that decides whether the scheduler starts firing triggers immediately or comes up in standby, and shutting the scheduler down cleanly onContextClosedEvent. -
Installs
JobDetail/CronTriggerpairs declaratively (CronJobInitializingBean), adding missing jobs, replacing changed jobs, scheduling missing triggers, and rescheduling changed cron expressions. -
Retires obsolete schedules declaratively (
JobDeletionInitializingBean), deleting jobs byname/groupat startup. -
Assembles cron jobs by allowlist (
CronJob+CronJobMapFactoryBean), so the set of jobs actually scheduled is the intersection of what the context defines and what the deployment explicitly permits. -
Exposes scheduler lifecycle over JMX (
SchedulerMXBean/SchedulerMonitor/SchedulerStatus), giving operators a start, standby, and status surface without adding a new control channel. -
References the
QRTZ_*schema as Liquibase (Quartz.changelog.xml), wired throughsmallmind-liquibaseso the metadata tables are created or migrated as part of the same application startup that initializes the scheduler. -
Ships the Quartz-authored DDL for every supported database (
tables_postgres.sql,tables_mysql_innodb.sql,tables_oracle.sql, and twenty more) undersrc/main/resources/quartz/so a deployment that manages its own migrations can load the schema directly.
-
It does not define jobs, triggers, or schedules. Those remain ordinary Quartz beans that the caller authors. This module starts the scheduler, resolves job beans, installs and retires trigger pairs, and logs firings; it does not describe the work.
-
It does not replace Quartz’s
StdSchedulerFactory.SpringSchedulerFactoryextends it, substituting a Spring-awareJobFactoryand adding Spring-lifecycle hooks. -
It does not ship a REST or web admin console.
SchedulerMonitoris a standard MBean; wrapping it in a transport is the caller’s decision. -
It does not support non-cron triggers in its declarative-install path.
CronJobInitializingBeanis specifically forCronTrigger. Simple triggers and calendar-based triggers can still be registered against the resolvedSchedulerbean directly; the declarative helpers just don’t cover them. -
It does not attempt cross-node orchestration itself. Clustering is a Quartz feature configured via
org.quartz.jobStore.isClustered; the shipped XML sets that flag totrue, but the coordination is Quartz’s, not this module’s.
| If you are … | Read, in this order |
|---|---|
… a service author adding your first scheduled job to an existing Spring
application that already imports |
At A Glance → Quick Start → Writing A Job → Declaring A Cron Schedule. |
… adopting scheduling in a service that does not yet import the Quartz XML configuration |
Installation → Conceptual Model → Spring Wiring → Quick Start. |
… writing a shared library that wants to describe jobs without dragging Quartz into the API |
Schedule-Base Reference only. Depend on |
… an operator who needs to pause a scheduler in production |
|
… investigating why a job ran but produced no log entry |
|
… investigating why a job bean cannot be resolved at firing time |
|
… retiring a job that no longer exists in code but is still firing from a clustered job store |
| Problem | Use | Notes |
|---|---|---|
Shared library wants to declare the shape of a scheduled unit of work |
|
No Quartz, no Spring on the classpath. |
Service wants to write a Quartz job with start / stop / count / outcome bookkeeping handled for it |
Subclass |
Implements both |
Service wants Quartz jobs to be Spring beans with prototype scope |
|
Enforced at firing time — non-prototype beans throw. |
Service wants the scheduler’s lifecycle tied to the Spring context |
|
Extends |
Service wants to declare cron jobs as Spring beans and have them installed at startup |
|
Installs or replaces; does not delete. |
Service wants to retire jobs that no longer belong in the scheduler |
|
Delete-only; runs at startup. |
Operator wants a JMX control surface for the scheduler |
|
|
Deployment wants Quartz tables created as part of application startup |
Import |
Uses the Quartz-authored DDL under |
smallmind-schedule publishes two artifacts. Depend on the smallest one that
fits your use.
Depend on this from shared libraries, interface modules, or any caller that needs to name the job contract without pulling in Quartz or Spring.
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>schedule-base</artifactId>
<version>${project.version}</version>
</dependency>Module name (for requires): org.smallmind.schedule.base
This artifact brings in smallmind-nutsnbolts (for SuccessOrFailure) and
nothing else.
The jar ships an explicit module descriptor that exports org.smallmind.schedule.base
and re-exports org.smallmind.nutsnbolts (requires transitive), because
SuccessOrFailure appears in the job contract. See
Module Path And Classpath for the repository-wide rules.
Depend on this from the application or service that actually runs the scheduler.
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>schedule-quartz</artifactId>
<version>${project.version}</version>
</dependency>Module name (for requires): org.smallmind.schedule.quartz
Brings in schedule-base, smallmind-nutsnbolts, smallmind-scribe-pen
(for structured logging), Quartz (org.quartz-scheduler:quartz), and the
Spring beans and context artifacts. The runtime classpath must also
include a JDBC driver for the database holding the QRTZ_* tables.
smallmind-liquibase and smallmind-persistence are optional dependencies
used only by the shipped Spring XML: quartz.xml imports
quartz-liquibase.xml, which runs SpringLiquibase on a
DriverManagerDataSource. An application that imports quartz.xml or
quartz-liquibase.xml declares both itself (and, on a module path,
requires org.smallmind.liquibase and org.smallmind.persistence).
|
Important
|
|
The jar ships an explicit module descriptor for org.smallmind.schedule.quartz that
exports org.smallmind.schedule.quartz, .jmx, and .spring. On the classpath the
descriptor is ignored. On a module path:
-
It re-exports (
requires transitive)org.smallmind.schedule.base,org.smallmind.nutsnbolts, andjava.management. It also requiresorg.quartz,spring.beans,spring.context, andorg.smallmind.scribe.pen. Quartz and Spring types (Scheduler,JobDetail,ApplicationContext,FactoryBean, and others) appear in its public signatures, but automatic modules are never re-exported, so requireorg.quartzand the Spring modules you use yourself. -
It opens
org.smallmind.schedule.quartzunconditionally, soquartz.xml,job.xml,quartz-liquibase.xml, andQuartz.changelog.xmlstay loadable by path from Spring and Liquibase. It opensorg.smallmind.schedule.quartz.springtospring.coreandspring.beans. -
Your job classes are constructed reflectively: by Spring when
SpringJobFactorysupplies them as prototype beans, or by Quartz if you install Quartz’s own job factory instead. Open each job package to the module that constructs it,spring.beans(withspring.core) ororg.quartz:opens com.example.job to spring.core, spring.beans;
Without it the scheduler starts but the job never runs. Quartz reports
An error occurred instantiating job to be executed … Failed to instantiate [com.example.job.TickJob]: Is the constructor accessible?only through its SLF4J log andSchedulerListener.schedulerError. -
org.quartzis automatic and cannot bring SLF4J into the module graph, so the application resolves it with--add-modules org.slf4j(or requires it). Without it creating theSpringSchedulerFactorybean fails withNoClassDefFoundError: org/slf4j/LoggerFactory.
See Module Path And Classpath for the repository-wide rules.
schedule/
pom.xml Aggregator POM
base/
pom.xml schedule-base artifact
src/main/java/
org/smallmind/schedule/base/
ProxyJob.java Framework-neutral job contract
quartz/
pom.xml schedule-quartz artifact
src/main/java/
org/smallmind/schedule/quartz/
QuartzProxyJob.java Abstract Quartz adapter
jmx/
SchedulerMXBean.java JMX management interface
SchedulerMonitor.java StandardMBean implementation
SchedulerStatus.java Enum of observable states
spring/
CronJob.java JobDetail + CronTrigger pair
CronJobInitializingBean.java Installs / replaces schedules
CronJobMapFactoryBean.java Allowlist-driven job map
FormattedSchedulerException.java printf-style SchedulerException
JobDeletionInitializingBean.java Retires jobs at startup
JobIdentifier.java name/group value object
SpringJobFactory.java Quartz JobFactory over Spring
SpringSchedulerFactory.java StdSchedulerFactory + Spring lifecycle
src/main/resources/
spring/org/smallmind/schedule/quartz/
quartz.xml Scheduler + JMX monitor wiring
quartz-liquibase.xml Liquibase migration for QRTZ_* tables
job.xml Example job + trigger + installer
liquibase/org/smallmind/schedule/quartz/
Quartz.changelog.xml Liquibase changelog
quartz/
tables_*.sql Quartz-authored DDL per databaseThe module ships three layered abstractions. Each layer is responsible for exactly one thing; understanding the split is the shortest path to using the module correctly.
ProxyJob-
The contract. A schedulable unit of work as seen by code that has no reason to know about Quartz. Declares
proceed()andcleanup(), the bookkeeping state (start time, stop time, count, status, throwables), and the two policy predicates (isEnabled(),logOnZeroCount()). Lives inschedule-base. QuartzProxyJob-
The Quartz adapter. An abstract class that implements
ProxyJobon top of Quartz’sInterruptableJob. Owns theexecute()method — the one Quartz calls when a trigger fires — and implements it as a fixed lifecycle: capture start time, register the running thread, callproceed(), catch exceptions, capture stop time, emit a structured log line, callcleanup(). Subclasses overrideproceed()and optionallycleanup(); everything else is fixed. SpringSchedulerFactory+SpringJobFactory+CronJobInitializingBean-
The Spring integration. Three collaborating beans, each responsible for a different slice of integration: factory wiring and lifecycle, job bean resolution at firing time, and declarative trigger installation.
- Bookkeeping invariants
-
QuartzProxyJobinitializesgetJobStatus()toSuccessOrFailure.SUCCESS. Any uncaughtExceptionthrown fromproceed()(other thanInterruptedException) flips the status toFAILUREthroughsetThrowable(throwable). AnInterruptedExceptionspecifically flips the status toINTERRUPTED. Subclasses may callsetThrowable(throwable, false)to record a non-fatal exception without changing the status. - Prototype invariant
-
Every Spring bean resolved by
SpringJobFactorymust be prototype-scoped. This is enforced at firing time; a singleton job bean throwsFormattedSchedulerException. The reason is that Quartz reusesJobinstances across firings only when the factory returns the same object, and the bookkeeping state onQuartzProxyJob— count, start time, stop time, throwables — is per-firing mutable state.
schedule-base contains exactly one public type. It is intentionally small.
Framework-neutral interface describing a schedulable unit of work. Methods:
isEnabled()-
Returns
trueif the job should be allowed to run on this firing. The host scheduler evaluates this before every firing and silently skips execution whenfalseis returned. Useful for config-driven toggles. logOnZeroCount()-
Returns
trueif a completion log line should be emitted even whengetCount()is zero. Jobs where an empty run is normal (and not worth logging) should returnfalse; jobs where an empty run is noteworthy should returntrue. getJobStatus()-
Returns a
SuccessOrFailurevalue reflecting the current or most recently recorded outcome. Three states:SUCCESS,FAILURE,INTERRUPTED. getCount()/incCount()-
A running count of items processed during the current or most recent execution. Incremented by the job body.
getStartTime()/getStopTime()-
LocalDateTimetimestamps for the most recent firing, ornullif the job has not yet run. getThrowables()-
Errors accumulated during the current or most recent execution, or
nullif none were recorded. setThrowable(Throwable)-
Records an error. The default contract is that this also marks the job as failed, but subclasses of the Quartz adapter have a two-argument variant that disables the failure transition.
proceed()-
Executes the job’s work. Throws
Exceptionif it cannot continue. cleanup()-
Post-execution housekeeping. Called after
proceed()returns, whether or not it threw.
ProxyJob is written to be implementable without any scheduling framework.
In practice, services implement the Quartz-integrated abstract subclass
(QuartzProxyJob), not the bare interface.
Abstract class that implements ProxyJob and Quartz’s InterruptableJob.
Subclasses override:
proceed()(required)-
The job body. Do the work here. Call
incCount()oraddToCount(int)to record progress. Throw exceptions if work cannot continue — uncaught non-InterruptedExceptionthrows becomeFAILURE;InterruptedExceptionbecomesINTERRUPTED. cleanup()(optional)-
Inherited
ProxyJob.cleanup()declaration; default Quartz adapter does not override it, so subclasses supply a concrete implementation (or an empty one). Called unconditionally in afinallyblock afterproceed(). Exceptions raised here are logged but do not propagate. isEnabled()(optional override)-
Defaults to
true. Override to gate firings on external configuration or runtime conditions. Whenfalse, the firing is skipped entirely — no start time, no log entry, nocleanup(). logOnZeroCount()(required — abstract onProxyJob)-
Return
trueif the completion log line should still be emitted whengetCount()is zero. Jobs where an empty run is normal should returnfalse.
Method contract highlights:
execute(JobExecutionContext)(final in practice — do not override)-
Called by Quartz when a trigger fires. Records
startTime, registersThread.currentThread()onthreadRef(sointerrupt()can reach it), callsproceed(), catches exceptions, clearsthreadRef, recordsstopTime, emits a structured completion log line, and callscleanup()in afinallyblock. interrupt()-
Standard Quartz interrupt hook. Calls
Thread.interrupt()on the thread currently running the job, if one is registered. incCount()/addToCount(int)-
Synchronized increment of the per-firing counter. Use
addToCountto record batched progress in a single operation. setThrowable(Throwable)/setThrowable(Throwable, boolean)-
Records an error. The one-argument form is a
ProxyJobcontract method and always marks the jobFAILURE. The two-argument form is aQuartzProxyJobextension: passfalseas the second argument to record an error for logging without changing the outcome.
Quartz JobFactory that sources job instances from a Spring
ApplicationContext. Constructed by SpringSchedulerFactory when the
context is injected.
Resolution algorithm (for a firing whose JobDetail points at job class
J and has key group.name):
-
getBeansOfType(J)— fetch every bean assignable toJ. -
If the result has exactly one entry, that is the resolved bean.
-
If the result has multiple entries, look for one whose bean name equals
jobKey.toString()(i.e.group.name). That is the resolved bean. -
If the result is empty, or multiple entries exist with no exact name match, throw
FormattedSchedulerExceptionwith a diagnostic message naming the job key, the job class, and the situation (no candidates / ambiguous candidates). -
In either of the first two cases, the resolved bean must be prototype-scoped; if it is not, throw
FormattedSchedulerException.
The factory also implements Closeable: when SpringSchedulerFactory
receives ContextClosedEvent, it closes the scheduler and then closes
the factory, which in turn closes the underlying ApplicationContext if
the context is itself closeable.
Extends org.quartz.impl.StdSchedulerFactory. Responsibilities:
- Spring lifecycle integration
-
Implements
ApplicationContextAwareandApplicationListener<ContextClosedEvent>. On context injection, it constructs aSpringJobFactorybound to the context. On context close, it callsscheduler.shutdown(true)(wait for executing jobs to finish) and then closes the job factory. JobFactoryinstallation-
getScheduler()is overridden to install theSpringJobFactoryon the returnedSchedulerbefore returning it. - Active-mode control
-
A setter
setActiveMode(OnOrOff)controls whether the scheduler is started (OnOrOff.ON) or placed in standby (OnOrOff.OFF) when first obtained. Default isON. Standby means triggers do not fire even though the scheduler is otherwise configured and ready; the JMX surface can later move it toSTARTED. - Constructor
-
Takes a
Propertiesinstance forwarded to theStdSchedulerFactoryconstructor. This is where all Quartz configuration — instance name, thread pool, job store, cluster settings, datasource — lives.
Value class pairing a JobDetail with a CronTrigger. A CronJob bean
is what deployments declare; CronJobMapFactoryBean collects the allowed
ones into a map and CronJobInitializingBean installs that map into the
scheduler.
A Spring FactoryBean<Map<JobDetail, List<CronTrigger>>> that is also a
BeanPostProcessor. Two responsibilities:
-
postProcessAfterInitializationscans every initialized bean. If a bean is aCronJob, its job key is compared (asgroup.name) against the configuredallowedJobIdslist. MatchingCronJobbeans have theirJobDetail/CronTriggerpair added to the map. Non-matching beans are returned unchanged. -
getObject()returns the accumulated map.
The allowlist pattern exists so that a deployment can ship a large,
shared catalog of CronJob beans and enable only the subset relevant to
each deployment environment (production, staging, cluster member, batch
node) by configuration.
Spring InitializingBean that synchronizes a Map<JobDetail,
List<CronTrigger>> with a Quartz Scheduler in afterPropertiesSet().
For each entry:
-
If the scheduler has no
JobDetailwith the target key,addJobis called. If it does have one, the twoJobDetailobjects are compared field-by-field (durability, recovery, concurrency, persistence, and the completeJobDataMap); if they differ,addJob(jobDetail, true)replaces the installed version. -
For each
CronTriggerin the entry’s list, if the scheduler has no trigger with that key,scheduleJob(trigger)is called. If it does have one, the cron expressions are compared; if they differ,rescheduleJobreplaces the trigger.
Errors on individual entries are logged (via smallmind-scribe-pen)
and do not abort processing of the remaining entries. This is
deliberate: a misconfigured trigger in one bean definition should not
prevent the rest of the schedule from installing.
Spring InitializingBean that deletes jobs from the scheduler in
afterPropertiesSet(). Takes a List<JobIdentifier> and calls
scheduler.deleteJob(new JobKey(name, group)) for each entry.
Typical use: a job has been removed from the codebase, but the clustered
job store still has its JobDetail and CronTrigger rows. Adding the
job’s name and group to a JobDeletionInitializingBean drops the stale
state on the next application startup. Once the cluster is fully restarted,
the deletion entry can be removed.
Value object with name and group properties. Used as list entries for
JobDeletionInitializingBean. Nothing more.
Extends org.quartz.SchedulerException with printf-style formatting. Four
constructors: no-args; format + args; throwable + format + args; throwable
alone. Used throughout SpringJobFactory so diagnostic messages carry the
offending job key, class name, or bean id inline.
A standard JMX MBean surface.
SchedulerMXBean-
Interface declaring
start(),standby(), andstatus(). The name ends inMXBeanso JMX treats it as ajavax.management.MXBean-compliant management interface. SchedulerMonitor-
StandardMBeanimplementation wrapping a QuartzScheduler.start()andstandby()delegate to the matching Quartz methods.status()inspects the scheduler’sisInStandbyMode,isStarted, andisShutdownflags, in that order of precedence, and returns the first matchingSchedulerStatusvalue. SchedulerStatus-
Enum with four constants:
STARTED,STANDBY,SHUTDOWN,UNKNOWN.UNKNOWNis returned when the scheduler’s state cannot be mapped to any of the other three.
The MBean is declared as a bean (schedulerMonitor) in the shipped
quartz.xml; registering it with the platform MBeanServer is the
caller’s responsibility (typically through Spring’s MBeanExporter).
The module ships three Spring XML files under
src/main/resources/spring/org/smallmind/schedule/quartz/. The build treats
src/main/resources/spring as a resource root, so they resolve on the
classpath at org/smallmind/schedule/quartz/*.xml.
Importable as:
<import resource="classpath:org/smallmind/schedule/quartz/quartz.xml"/>Defines three beans:
schedulerFactory(SpringSchedulerFactory)-
The factory. Its constructor takes a
<props>block with the full Quartz configuration: instance name, thread pool (defaults toSimpleThreadPool, four threads), RMI export enabled, job storeorg.quartz.impl.jdbcjobstore.JobStoreTXwithStdJDBCDelegate, aQRTZ_table prefix,useProperties=true, clustering enabled with a 20-second check-in interval, and a datasource block keyed off${jdbc.driver.classname},${jdbc.url.quartz},${jdbc.username.quartz}, and${jdbc.password.quartz}. The factory depends onquartzLiquibaseso theQRTZ_*tables are guaranteed to exist before the factory tries to touch them. TheinterruptJobsOnShutdownandinterruptJobsOnShutdownWithWaitflags are bothtrue, meaningshutdown(true)interrupts running jobs and waits for them to return. scheduler-
Obtained from
schedulerFactory.getScheduler(). Registered withdestroy-method="shutdown"so it shuts down on context close even ifSpringSchedulerFactory’s `ContextClosedEventlistener does not fire first. schedulerMonitor(SchedulerMonitor)-
Constructed with the
schedulerbean. Ready for export under anObjectNameof the caller’s choosing.
|
Note
|
The shipped |
Imported transitively by quartz.xml. Defines two beans:
quartzDataSource(org.smallmind.persistence.sql.DriverManagerDataSource)-
A standalone datasource dedicated to the schema migration. Keyed off the same
${jdbc.*.quartz}property names as the Quartz datasource inquartz.xml. quartzLiquibase(org.smallmind.liquibase.spring.SpringLiquibase)-
A
smallmind-liquibasemigrator that runsQuartz.changelog.xmlagainstquartzDataSourcewithgoal=UPDATE. This is the beanschedulerFactorydepends on.
job.xml is a template, not an importable configuration; it uses
placeholder strings (group, nameJob, jobClass) as literal values.
Use it as a copy-paste skeleton for defining a scheduled job in your own
Spring configuration. The four beans it declares are the full pattern:
-
A
JobDetailImplbean describing the job class and metadata. -
A
CronTriggerImplbean bound to that job detail with a cron expression. -
The job bean itself (the subclass of
QuartzProxyJob), declared asscope="prototype". -
A
CronJobInitializingBeanpopulated with a map whose entry ties the job detail to a list of triggers.
The shipped schedulerMonitor bean implements SchedulerMXBean:
public interface SchedulerMXBean {
void start () throws Exception;
void standby () throws Exception;
SchedulerStatus status () throws Exception;
}Expose it through Spring’s MBeanExporter, jolokia, or any other
mechanism that registers MBeans with the platform MBeanServer. Once
registered, an operator with JMX access can:
-
Call
status()to inspect whether the scheduler isSTARTED,STANDBY,SHUTDOWN, orUNKNOWN. -
Call
standby()to halt all trigger firing without shutting down the scheduler or redeploying the service. Jobs already executing continue to run until they return; no new firings are scheduled. ExistingJobDetail/CronTriggerregistrations are preserved. -
Call
start()to return a standby scheduler to active firing.
| Status | Meaning |
|---|---|
|
The scheduler is running and triggers are firing. |
|
The scheduler is paused; trigger firings are suppressed but all job and trigger registrations are preserved. |
|
The scheduler has been stopped and cannot be restarted. Obtain a new scheduler from the factory to resume firing. |
|
The scheduler’s state did not match |
This section walks through adding one scheduled job to a Spring service
that imports the shipped quartz.xml.
A job is a subclass of QuartzProxyJob that overrides proceed() and
cleanup(). Below is a minimal, realistic example: a job that advances a
counter of records processed from a queue.
package com.example.service.schedule;
import java.util.List;
import org.quartz.DisallowConcurrentExecution;
import org.smallmind.schedule.quartz.QuartzProxyJob;
@DisallowConcurrentExecution // (1)
public class QueueDrainJob extends QuartzProxyJob {
private final QueueClient queueClient;
public QueueDrainJob (QueueClient queueClient) { // (2)
this.queueClient = queueClient;
}
@Override
public boolean logOnZeroCount () { // (3)
return false;
}
@Override
public void proceed ()
throws Exception {
List<Message> batch;
while (!(batch = queueClient.poll(100)).isEmpty()) {
for (Message message : batch) {
try {
queueClient.process(message);
incCount(); // (4)
} catch (TransientException transientException) {
setThrowable(transientException, false); // (5)
}
}
}
}
@Override
public void cleanup () {
}
}-
Quartz’s
@DisallowConcurrentExecutionprevents two firings of the same job from overlapping. Combined with the prototype-scoped bean requirement, this is the standard way to get per-firing isolation. -
Constructor injection — ordinary Spring. The bean will be prototype-scoped in
applicationContext.xml. -
Return
falsebecause an idle queue is a normal state and does not warrant a log line. -
Record each processed message.
getCount()will report this value in the completion log line and through JMX if the subclass is exposed there. -
Record the exception in the per-firing list without flipping the outcome to
FAILURE, because a transient failure on one message is expected and should not mark the whole firing as failed.
The job bean must be prototype-scoped:
<bean id="scheduled.queueDrainJob" class="com.example.service.schedule.QueueDrainJob" scope="prototype">
<constructor-arg ref="queueClient"/>
</bean>The bean id matches the job key (group.name) so that SpringJobFactory
resolves it unambiguously when multiple jobs share the same class — see
Job Bean Resolution.
Declare a JobDetail and a CronTrigger and hand them to
CronJobInitializingBean.
<bean id="scheduled.queueDrainDetail" class="org.quartz.impl.JobDetailImpl">
<property name="description" value="Drains the pending-message queue"/>
<property name="group" value="scheduled"/>
<property name="name" value="queueDrainJob"/>
<property name="jobClass" value="com.example.service.schedule.QueueDrainJob"/>
<property name="durability" value="true"/>
<property name="requestsRecovery" value="false"/> <!--(1)-->
</bean>
<bean id="scheduled.queueDrainTrigger" class="org.quartz.impl.triggers.CronTriggerImpl">
<property name="description" value="Every five minutes"/>
<property name="group" value="scheduled"/>
<property name="name" value="queueDrainTrigger"/>
<property name="jobGroup" value="scheduled"/>
<property name="jobName" value="queueDrainJob"/>
<property name="cronExpression" value="0 0/5 * * * ?"/>
</bean>
<bean class="org.smallmind.schedule.quartz.spring.CronJobInitializingBean">
<property name="scheduler" ref="scheduler"/>
<property name="jobMap">
<map>
<entry key-ref="scheduled.queueDrainDetail">
<list>
<ref bean="scheduled.queueDrainTrigger"/>
</list>
</entry>
</map>
</property>
</bean>-
Set to
trueonly if the clustered deployment should attempt to recover a failed firing on another node. For most scheduled batch work — where the next firing will do the remaining work — leave thisfalse.
On context startup, CronJobInitializingBean inspects the scheduler’s
job store: if no scheduled.queueDrainJob is present, it adds one; if
the installed JobDetail differs, it replaces it; if the trigger is
missing, it schedules it; if the cron expression has changed, it
reschedules.
For services that ship a catalog of CronJob beans and enable only a
subset per environment, the allowlist pattern is:
<bean id="scheduled.queueDrainCronJob" class="org.smallmind.schedule.quartz.spring.CronJob">
<property name="jobDetail" ref="scheduled.queueDrainDetail"/>
<property name="cronTrigger" ref="scheduled.queueDrainTrigger"/>
</bean>
<bean id="scheduled.otherCronJob" class="org.smallmind.schedule.quartz.spring.CronJob">
<property name="jobDetail" ref="scheduled.otherDetail"/>
<property name="cronTrigger" ref="scheduled.otherTrigger"/>
</bean>
<bean id="cronJobMap" class="org.smallmind.schedule.quartz.spring.CronJobMapFactoryBean">
<property name="allowedJobIds">
<list>
<value>scheduled.queueDrainJob</value> <!--(1)-->
</list>
</property>
</bean>
<bean class="org.smallmind.schedule.quartz.spring.CronJobInitializingBean">
<property name="scheduler" ref="scheduler"/>
<property name="jobMap" ref="cronJobMap"/>
</bean>-
Only the
scheduled.queueDrainJobkey is admitted. The otherCronJobbean is instantiated — it is a Spring bean in the context — but its job / trigger pair is silently dropped from the map and never reaches the scheduler.
The allowlist entries match JobDetail keys (group.name), not
bean ids. Check CronJob.getJobDetail().getKey() when in doubt.
A clustered job store remembers jobs across deployments. Deleting a
CronJob bean from Spring XML does not remove the row — the scheduler
will still fire it. Retire the job explicitly:
<bean class="org.smallmind.schedule.quartz.spring.JobDeletionInitializingBean">
<property name="scheduler" ref="scheduler"/>
<property name="jobIdentifierList">
<list>
<bean class="org.smallmind.schedule.quartz.spring.JobIdentifier">
<property name="group" value="scheduled"/>
<property name="name" value="legacyExportJob"/>
</bean>
</list>
</property>
</bean>Once every cluster member has deployed the configuration with the deletion entry and run at least once, the entry can be removed.
This section documents edge cases, invariants, and runtime details that readers will look for by name.
QuartzProxyJob.execute() emits at most one structured log line per
firing. The decision tree is:
-
If
isEnabled()returnedfalse, nothing is logged. The firing was silently skipped. -
If the job was interrupted (
InterruptedExceptioncaught inproceed()), anINFOline is emitted through the subclass’sscribe-penlogger with the templateJob(<simpleName>) start(<start>) has been interrupted. -
Otherwise, if the outcome was
FAILURE, orgetCount() > 0, orlogOnZeroCount()returnedtrue, a line is emitted with the templateJob(<simpleName>) start(<start>) stop(<stop>) count(<count>) state(<status>). The log level isWARNwhen the status isFAILURE,INFOotherwise. -
Otherwise (status
SUCCESS, count zero,logOnZeroCount()returnedfalse) no line is emitted. An idle job runs silently.
The logger is obtained from LoggerManager.getLogger(this.getClass()),
so each job class has its own logger name for filtering.
Inside QuartzProxyJob.execute():
-
InterruptedExceptiontransitions status toINTERRUPTED. It does not go throughsetThrowable; no entry is added to the throwable list. -
Any other
Exceptionis passed tosetThrowable(exception), which appends it to the throwable list, sets status toFAILURE, and logs it immediately atERRORlevel. -
cleanup()is invoked in afinallyblock. Any exception fromcleanup()is caught, logged atERRORlevel, and swallowed — it does not propagate and does not change the job’s status.
A subclass that wants to record an error without marking the firing as
failed must call setThrowable(throwable, false) directly rather than
let an exception bubble out of proceed().
SpringJobFactory.newJob is called by Quartz each time a trigger fires.
Its resolution rules, in order:
-
applicationContext.getBeansOfType(jobClass)returns zero beans →FormattedSchedulerException"No job(<key>) of type(<class>) is present in the application context". -
Returns exactly one bean → that bean is used, after verifying it is prototype-scoped.
-
Returns multiple beans → the factory searches for one whose bean name equals
jobDetail.getKey().toString()(i.e.group.name). If found, that one is used after verifying it is prototype-scoped. If not,FormattedSchedulerException"Multiple jobs of type(<class>) are present in the application context, but none with an exact id(<key>)". -
The resolved bean must be prototype-scoped;
applicationContext.isPrototype(beanName)must returntrue. A singleton or request-scoped bean throwsFormattedSchedulerException"The matching job(<key>) with id(<beanId>) in the application context is not a prototype bean".
The practical consequence is the naming convention: declare job beans
with id="group.name" matching the JobKey of the corresponding
JobDetail. If every job class has exactly one bean in the context,
resolution succeeds on step 2 and the bean id is unconstrained. If
multiple jobs share a class, resolution succeeds on step 3 only when
the bean ids are group.name.
On entry to execute(), the calling thread (the Quartz worker) is
stored in threadRef (an AtomicReference<Thread>). On exit, whether
normal or exceptional, threadRef is cleared. interrupt() reads
threadRef and calls Thread.interrupt() on it if non-null.
Consequences:
-
Calling
interrupt()between firings is a no-op. -
Calling
interrupt()concurrently with a firing interrupts the worker thread.proceed()must either cooperate with interruption (checkThread.interrupted()in loops, propagateInterruptedExceptionfrom blocking calls) or the interrupt is silently lost. -
scheduler.shutdown(true)(as configured byinterruptJobsOnShutdownWithWait=truein the shippedquartz.xml) reaches the worker thread through Quartz’s own interrupt machinery, which in turn callsinterrupt()on the job.
CronJobInitializingBean.afterPropertiesSet() is idempotent within a
single startup but is not safe to run concurrently on multiple
cluster members. The decision to add, replace, schedule, or reschedule
is based on reading the installed state, deciding, and writing — a
classic check-then-act race.
In practice, Quartz’s clustered job store serializes writes, so the
worst case is that two cluster members both see no installed trigger,
both call scheduleJob, and one of them gets a Quartz duplicate-key
error. The error is logged and the rest of the configuration proceeds.
The net effect is correct: exactly one copy of each trigger ends up in
the store.
If you want deterministic single-writer behavior, stagger cluster member startups or keep the bean on a single "leader" deployment only.
When CronJobInitializingBean finds an installed JobDetail with the
same key, it uses isSame(desired, installed) to decide whether to
replace. The comparison covers:
-
isDurable -
requestsRecovery -
isConcurrentExecutionDisallowed -
isPersistJobDataAfterExecution -
The full
JobDataMap: identical set of keys, identical values under each key (viaObject.equals).
Any difference triggers addJob(jobDetail, true), which replaces the
stored definition. The comparison does not include description or
job class — change the class, and the installed JobDetail stays
wrong. This is rare in practice because the class is what caused the
change in the first place; either evict the job explicitly through
JobDeletionInitializingBean first, or bump a JobDataMap entry to
force a replace.
Only the cron expression is compared. Changes to misfire instructions, time zone, priority, or description do not trigger a reschedule. Work around this by appending a version suffix to the cron expression when you need to force a reschedule, or by evicting the trigger first (delete the job and re-add it on the next deployment).
schedule-quartz brings in Quartz, Spring beans, Spring context, and
smallmind-scribe-pen. If you use the Liquibase wiring, you additionally
need smallmind-liquibase and its transitive Liquibase core jar on the
classpath. The quartzDataSource bean in quartz-liquibase.xml uses
org.smallmind.persistence.sql.DriverManagerDataSource, which requires
smallmind-persistence to be present.
SpringSchedulerFactory is declared with depends-on="quartzLiquibase"
so the QRTZ_* tables exist before Quartz tries to query them. If you
replace quartzLiquibase with your own migration tool (Flyway, a
standalone Liquibase runner, hand-managed DDL), you must preserve the
ordering: the scheduler cannot be constructed before its tables exist.
Two mechanisms wait for executing jobs to finish:
-
The
schedulerbean is declared withdestroy-method="shutdown", which callsscheduler.shutdown()(no wait). -
SpringSchedulerFactory.onApplicationEvent(ContextClosedEvent)callsscheduler.shutdown(true)(wait).
Both paths execute on context close. The true argument in path 2
dominates: shutdown(true) waits for executing jobs, and Quartz
tolerates a second shutdown() call as a no-op. The
interruptJobsOnShutdown properties in quartz.xml additionally cause
Quartz to call interrupt() on InterruptableJob instances before
waiting, so well-behaved jobs return quickly.
All module-level logging goes through smallmind-scribe-pen. The
logger name is the job class’s fully-qualified name for job execution,
and the class name of the bean (CronJobInitializingBean,
SpringSchedulerFactory) for infrastructure events. Configure the
filter level for these names explicitly in your scribe configuration
if you want to suppress the one-line-per-firing completion output.
The shipped schedulerMonitor bean is constructed but not registered.
Add a Spring MBeanExporter bean to expose it; the MBean’s
ObjectName is the caller’s choice. A common pattern:
<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="com.example:type=Scheduler,name=Default" value-ref="schedulerMonitor"/>
</map>
</property>
<property name="server" ref="platformMBeanServer"/>
</bean>
<bean id="platformMBeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean">
<property name="locateExistingServerIfPossible" value="true"/>
</bean>- Declarative install covers cron triggers only
-
CronJobInitializingBeanis specifically a cron-trigger installer.SimpleTrigger,DailyTimeIntervalTrigger, and calendar-interval triggers must be installed against the resolvedSchedulerbean directly. This is a narrowing choice — most recurring service work is naturally cron-shaped. - Trigger comparison is cron-expression-only
-
CronJobInitializingBeanreplaces a trigger only when its cron expression has changed. Changes to misfire instructions, time zone, or priority are not detected. Work around by forcing a cron-expression change (e.g. append a no-op space normalization) or by deleting and re-adding the trigger. - JobDetail comparison ignores class and description
-
Durability, recovery, concurrency, persistence, and the full
JobDataMapare compared; theClass<? extends Job>and description are not. A change to the job class alone does not trigger a replace. Change aJobDataMapentry to force a replace. - Allowlist matches on
group.name, not bean id -
CronJobMapFactoryBeancompares against theJobDetail.getKey()of theCronJobbean, not its Spring bean id. If the two differ, the allowlist entry must be the job key, not the bean id. - Prototype scope is enforced at firing time, not at startup
-
A singleton job bean surfaces only when a trigger actually fires. Include every scheduled job in a smoke test that forces at least one firing if you want catch this misconfiguration during deployment validation.
- Single active-mode enum
-
SpringSchedulerFactory.setActiveMode(OnOrOff)has exactly two values. There is no third "leave whatever state Quartz’s own startup produced" option. If you want deployment-specific nuance (e.g. "start on the primary, standby on replicas"), compute the value externally and inject it. SchedulerMonitorexposes three operations, not nine-
The JMX surface is intentionally narrow: start, standby, status. There is no pause-trigger-by-name, no trigger-now, no remove-job, and no last-fired timestamp. Operations that target individual jobs are available through the Quartz
Schedulerbean programmatically; wrap them in your own MBean if you need them over JMX.
ProxyJob.setThrowable(Throwable) contract differs from the two-argument
form::
The one-argument form, as implemented by QuartzProxyJob, always
marks the job FAILURE. Only the two-argument
setThrowable(Throwable, boolean) extension — which is not on the
ProxyJob interface — allows recording an exception without
changing the outcome.
-
BATCH.adoc — longer-running, parameterized batch jobs backed by Spring Batch. Same shape: framework-neutral API artifact plus Spring Batch integration artifact.
-
LIQUIBASE.adoc — the
SpringLiquibasebean referenced byquartz-liquibase.xml. -
NUTSNBOLTS.adoc — source of
SuccessOrFailureandOnOrOff, used byProxyJobandSpringSchedulerFactory.