Skip to content

Latest commit

 

History

History
1291 lines (1051 loc) · 53 KB

SCHEDULE.adoc

File metadata and controls

1291 lines (1051 loc) · 53 KB

SmallMind Schedule

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. Implements ProxyJob as an abstract InterruptableJob base class, wires a Quartz Scheduler into a Spring ApplicationContext, 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 the QRTZ_* 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:

  1. A SchedulerFactory — typically the JDBC-backed StdSchedulerFactory — configured from a Properties instance with twenty-plus entries covering the instance name, thread pool, job store, datasource, clustering, and RMI exposure.

  2. A bridge between Spring and Quartz job instantiation. Out of the box, Quartz instantiates Job classes via Class.newInstance(); a Spring service wants dependency-injected @Autowired fields and prototype-scoped beans, which requires a custom org.quartz.spi.JobFactory.

  3. 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.

  4. Declarative schedule management. Every Quartz job is a JobDetail paired with one or more Trigger instances, keyed by name and group. 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.

  5. 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.

  6. 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.

  7. A database schema. The JobStoreTX job store requires the QRTZ_* 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 (ProxyJob in schedule-base) so shared libraries can describe a schedulable unit of work without referencing Quartz.

  • Implements ProxyJob over Quartz’s InterruptableJob (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 an activeMode toggle that decides whether the scheduler starts firing triggers immediately or comes up in standby, and shutting the scheduler down cleanly on ContextClosedEvent.

  • Installs JobDetail/CronTrigger pairs declaratively (CronJobInitializingBean), adding missing jobs, replacing changed jobs, scheduling missing triggers, and rescheduling changed cron expressions.

  • Retires obsolete schedules declaratively (JobDeletionInitializingBean), deleting jobs by name/group at 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 through smallmind-liquibase so 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) under src/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. SpringSchedulerFactory extends it, substituting a Spring-aware JobFactory and adding Spring-lifecycle hooks.

  • It does not ship a REST or web admin console. SchedulerMonitor is 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. CronJobInitializingBean is specifically for CronTrigger. Simple triggers and calendar-based triggers can still be registered against the resolved Scheduler bean 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 to true, 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 quartz.xml

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 schedule-base, implement ProxyJob, and let the consuming application adapt to Quartz.

… an operator who needs to pause a scheduler in production

JMX Control → Scheduler States.

… investigating why a job ran but produced no log entry

Completion Log Rules.

… investigating why a job bean cannot be resolved at firing time

Job Bean Resolution.

… retiring a job that no longer exists in code but is still firing from a clustered job store

Retiring Obsolete Jobs.

Problem Use Notes

Shared library wants to declare the shape of a scheduled unit of work

ProxyJob (in schedule-base)

No Quartz, no Spring on the classpath.

Service wants to write a Quartz job with start / stop / count / outcome bookkeeping handled for it

Subclass QuartzProxyJob and override proceed()

Implements both ProxyJob and Quartz’s InterruptableJob.

Service wants Quartz jobs to be Spring beans with prototype scope

SpringJobFactory, installed by SpringSchedulerFactory

Enforced at firing time — non-prototype beans throw.

Service wants the scheduler’s lifecycle tied to the Spring context

SpringSchedulerFactory

Extends StdSchedulerFactory; drops in as a factory bean.

Service wants to declare cron jobs as Spring beans and have them installed at startup

CronJob + CronJobMapFactoryBean + CronJobInitializingBean

Installs or replaces; does not delete.

Service wants to retire jobs that no longer belong in the scheduler

JobDeletionInitializingBean

Delete-only; runs at startup.

Operator wants a JMX control surface for the scheduler

SchedulerMonitor (exposes SchedulerMXBean)

start, standby, status only.

Deployment wants Quartz tables created as part of application startup

Import quartz-liquibase.xml (referenced by quartz.xml)

Uses the Quartz-authored DDL under src/main/resources/quartz/.

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

schedule-quartz ships its resources at org/smallmind/schedule/quartz/quartz.xml, org/smallmind/schedule/quartz/quartz-liquibase.xml, job.xml, and org/smallmind/schedule/quartz/Quartz.changelog.xml on the classpath. The build treats src/main/resources/spring and src/main/resources/liquibase as resource roots, so the spring/ and liquibase/ directory names are not part of the classpath path.

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, and java.management. It also requires org.quartz, spring.beans, spring.context, and org.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 require org.quartz and the Spring modules you use yourself.

  • It opens org.smallmind.schedule.quartz unconditionally, so quartz.xml, job.xml, quartz-liquibase.xml, and Quartz.changelog.xml stay loadable by path from Spring and Liquibase. It opens org.smallmind.schedule.quartz.spring to spring.core and spring.beans.

  • Your job classes are constructed reflectively: by Spring when SpringJobFactory supplies 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 (with spring.core) or org.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 and SchedulerListener.schedulerError.

  • org.quartz is 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 the SpringSchedulerFactory bean fails with NoClassDefFoundError: 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 database

The 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() and cleanup(), the bookkeeping state (start time, stop time, count, status, throwables), and the two policy predicates (isEnabled(), logOnZeroCount()). Lives in schedule-base.

QuartzProxyJob

The Quartz adapter. An abstract class that implements ProxyJob on top of Quartz’s InterruptableJob. Owns the execute() method — the one Quartz calls when a trigger fires — and implements it as a fixed lifecycle: capture start time, register the running thread, call proceed(), catch exceptions, capture stop time, emit a structured log line, call cleanup(). Subclasses override proceed() and optionally cleanup(); 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

QuartzProxyJob initializes getJobStatus() to SuccessOrFailure.SUCCESS. Any uncaught Exception thrown from proceed() (other than InterruptedException) flips the status to FAILURE through setThrowable(throwable). An InterruptedException specifically flips the status to INTERRUPTED. Subclasses may call setThrowable(throwable, false) to record a non-fatal exception without changing the status.

Prototype invariant

Every Spring bean resolved by SpringJobFactory must be prototype-scoped. This is enforced at firing time; a singleton job bean throws FormattedSchedulerException. The reason is that Quartz reuses Job instances across firings only when the factory returns the same object, and the bookkeeping state on QuartzProxyJob — 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 true if the job should be allowed to run on this firing. The host scheduler evaluates this before every firing and silently skips execution when false is returned. Useful for config-driven toggles.

logOnZeroCount()

Returns true if a completion log line should be emitted even when getCount() is zero. Jobs where an empty run is normal (and not worth logging) should return false; jobs where an empty run is noteworthy should return true.

getJobStatus()

Returns a SuccessOrFailure value 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()

LocalDateTime timestamps for the most recent firing, or null if the job has not yet run.

getThrowables()

Errors accumulated during the current or most recent execution, or null if 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 Exception if 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() or addToCount(int) to record progress. Throw exceptions if work cannot continue — uncaught non-InterruptedException throws become FAILURE; InterruptedException becomes INTERRUPTED.

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 a finally block after proceed(). 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. When false, the firing is skipped entirely — no start time, no log entry, no cleanup().

logOnZeroCount() (required — abstract on ProxyJob)

Return true if the completion log line should still be emitted when getCount() is zero. Jobs where an empty run is normal should return false.

Method contract highlights:

execute(JobExecutionContext) (final in practice — do not override)

Called by Quartz when a trigger fires. Records startTime, registers Thread.currentThread() on threadRef (so interrupt() can reach it), calls proceed(), catches exceptions, clears threadRef, records stopTime, emits a structured completion log line, and calls cleanup() in a finally block.

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 addToCount to record batched progress in a single operation.

setThrowable(Throwable) / setThrowable(Throwable, boolean)

Records an error. The one-argument form is a ProxyJob contract method and always marks the job FAILURE. The two-argument form is a QuartzProxyJob extension: pass false as 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):

  1. getBeansOfType(J) — fetch every bean assignable to J.

  2. If the result has exactly one entry, that is the resolved bean.

  3. If the result has multiple entries, look for one whose bean name equals jobKey.toString() (i.e. group.name). That is the resolved bean.

  4. If the result is empty, or multiple entries exist with no exact name match, throw FormattedSchedulerException with a diagnostic message naming the job key, the job class, and the situation (no candidates / ambiguous candidates).

  5. 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 ApplicationContextAware and ApplicationListener<ContextClosedEvent>. On context injection, it constructs a SpringJobFactory bound to the context. On context close, it calls scheduler.shutdown(true) (wait for executing jobs to finish) and then closes the job factory.

JobFactory installation

getScheduler() is overridden to install the SpringJobFactory on the returned Scheduler before 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 is ON. Standby means triggers do not fire even though the scheduler is otherwise configured and ready; the JMX surface can later move it to STARTED.

Constructor

Takes a Properties instance forwarded to the StdSchedulerFactory constructor. 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:

  • postProcessAfterInitialization scans every initialized bean. If a bean is a CronJob, its job key is compared (as group.name) against the configured allowedJobIds list. Matching CronJob beans have their JobDetail / CronTrigger pair 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 JobDetail with the target key, addJob is called. If it does have one, the two JobDetail objects are compared field-by-field (durability, recovery, concurrency, persistence, and the complete JobDataMap); if they differ, addJob(jobDetail, true) replaces the installed version.

  • For each CronTrigger in 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, rescheduleJob replaces 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(), and status(). The name ends in MXBean so JMX treats it as a javax.management.MXBean-compliant management interface.

SchedulerMonitor

StandardMBean implementation wrapping a Quartz Scheduler. start() and standby() delegate to the matching Quartz methods. status() inspects the scheduler’s isInStandbyMode, isStarted, and isShutdown flags, in that order of precedence, and returns the first matching SchedulerStatus value.

SchedulerStatus

Enum with four constants: STARTED, STANDBY, SHUTDOWN, UNKNOWN. UNKNOWN is 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 to SimpleThreadPool, four threads), RMI export enabled, job store org.quartz.impl.jdbcjobstore.JobStoreTX with StdJDBCDelegate, a QRTZ_ 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 on quartzLiquibase so the QRTZ_* tables are guaranteed to exist before the factory tries to touch them. The interruptJobsOnShutdown and interruptJobsOnShutdownWithWait flags are both true, meaning shutdown(true) interrupts running jobs and waits for them to return.

scheduler

Obtained from schedulerFactory.getScheduler(). Registered with destroy-method="shutdown" so it shuts down on context close even if SpringSchedulerFactory’s `ContextClosedEvent listener does not fire first.

schedulerMonitor (SchedulerMonitor)

Constructed with the scheduler bean. Ready for export under an ObjectName of the caller’s choosing.

Note

The shipped quartz.xml is a template, not a hardened configuration. Most deployments will need to override the thread pool size, the RMI export flag, or the clustering interval. The normal pattern is to copy quartz.xml into the consuming application and modify it in place rather than import it verbatim. The import form above is fine for a first integration.

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 in quartz.xml.

quartzLiquibase (org.smallmind.liquibase.spring.SpringLiquibase)

A smallmind-liquibase migrator that runs Quartz.changelog.xml against quartzDataSource with goal=UPDATE. This is the bean schedulerFactory depends 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:

  1. A JobDetailImpl bean describing the job class and metadata.

  2. A CronTriggerImpl bean bound to that job detail with a cron expression.

  3. The job bean itself (the subclass of QuartzProxyJob), declared as scope="prototype".

  4. A CronJobInitializingBean populated 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 is STARTED, STANDBY, SHUTDOWN, or UNKNOWN.

  • 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. Existing JobDetail / CronTrigger registrations are preserved.

  • Call start() to return a standby scheduler to active firing.

Status Meaning

STARTED

The scheduler is running and triggers are firing.

STANDBY

The scheduler is paused; trigger firings are suppressed but all job and trigger registrations are preserved.

SHUTDOWN

The scheduler has been stopped and cannot be restarted. Obtain a new scheduler from the factory to resume firing.

UNKNOWN

The scheduler’s state did not match isInStandbyMode, isStarted, or isShutdown. Typically indicates the scheduler has been constructed but not yet started.

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 () {
  }
}
  1. Quartz’s @DisallowConcurrentExecution prevents 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.

  2. Constructor injection — ordinary Spring. The bean will be prototype-scoped in applicationContext.xml.

  3. Return false because an idle queue is a normal state and does not warrant a log line.

  4. Record each processed message. getCount() will report this value in the completion log line and through JMX if the subclass is exposed there.

  5. 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>
  1. Set to true only 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 this false.

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>
  1. Only the scheduled.queueDrainJob key is admitted. The other CronJob bean 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:

  1. If isEnabled() returned false, nothing is logged. The firing was silently skipped.

  2. If the job was interrupted (InterruptedException caught in proceed()), an INFO line is emitted through the subclass’s scribe-pen logger with the template Job(<simpleName>) start(<start>) has been interrupted.

  3. Otherwise, if the outcome was FAILURE, or getCount() > 0, or logOnZeroCount() returned true, a line is emitted with the template Job(<simpleName>) start(<start>) stop(<stop>) count(<count>) state(<status>). The log level is WARN when the status is FAILURE, INFO otherwise.

  4. Otherwise (status SUCCESS, count zero, logOnZeroCount() returned false) 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():

  • InterruptedException transitions status to INTERRUPTED. It does not go through setThrowable; no entry is added to the throwable list.

  • Any other Exception is passed to setThrowable(exception), which appends it to the throwable list, sets status to FAILURE, and logs it immediately at ERROR level.

  • cleanup() is invoked in a finally block. Any exception from cleanup() is caught, logged at ERROR level, 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:

  1. applicationContext.getBeansOfType(jobClass) returns zero beans → FormattedSchedulerException "No job(<key>) of type(<class>) is present in the application context".

  2. Returns exactly one bean → that bean is used, after verifying it is prototype-scoped.

  3. 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>)".

  4. The resolved bean must be prototype-scoped; applicationContext.isPrototype(beanName) must return true. A singleton or request-scoped bean throws FormattedSchedulerException "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 (check Thread.interrupted() in loops, propagate InterruptedException from blocking calls) or the interrupt is silently lost.

  • scheduler.shutdown(true) (as configured by interruptJobsOnShutdownWithWait=true in the shipped quartz.xml) reaches the worker thread through Quartz’s own interrupt machinery, which in turn calls interrupt() 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 (via Object.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:

  1. The scheduler bean is declared with destroy-method="shutdown", which calls scheduler.shutdown() (no wait).

  2. SpringSchedulerFactory.onApplicationEvent(ContextClosedEvent) calls scheduler.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

CronJobInitializingBean is specifically a cron-trigger installer. SimpleTrigger, DailyTimeIntervalTrigger, and calendar-interval triggers must be installed against the resolved Scheduler bean directly. This is a narrowing choice — most recurring service work is naturally cron-shaped.

Trigger comparison is cron-expression-only

CronJobInitializingBean replaces 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 JobDataMap are compared; the Class<? extends Job> and description are not. A change to the job class alone does not trigger a replace. Change a JobDataMap entry to force a replace.

Allowlist matches on group.name, not bean id

CronJobMapFactoryBean compares against the JobDetail.getKey() of the CronJob bean, 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.

SchedulerMonitor exposes 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 Scheduler bean 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 SpringLiquibase bean referenced by quartz-liquibase.xml.

  • NUTSNBOLTS.adoc — source of SuccessOrFailure and OnOrOff, used by ProxyJob and SpringSchedulerFactory.