0
# Quartz Job Scheduler
1
2
Quartz is a comprehensive enterprise job scheduling library for Java applications that provides robust scheduling capabilities including cron-like scheduling, trigger management, job persistence, clustering support, and transaction management. The library is designed for maximum flexibility and can be integrated into applications ranging from simple standalone programs to large-scale enterprise systems.
3
4
## Package Information
5
6
- **Package Name**: quartz
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Group ID**: org.quartz-scheduler
10
- **Artifact ID**: quartz
11
- **Version**: 2.5.0
12
- **Installation**:
13
```xml
14
<dependency>
15
<groupId>org.quartz-scheduler</groupId>
16
<artifactId>quartz</artifactId>
17
<version>2.5.0</version>
18
</dependency>
19
```
20
21
## Core Imports
22
23
```java
24
import org.quartz.Job;
25
import org.quartz.JobBuilder;
26
import org.quartz.JobDetail;
27
import org.quartz.JobExecutionContext;
28
import org.quartz.JobExecutionException;
29
import org.quartz.Scheduler;
30
import org.quartz.SchedulerFactory;
31
import org.quartz.Trigger;
32
import org.quartz.TriggerBuilder;
33
import org.quartz.impl.StdSchedulerFactory;
34
35
import static org.quartz.JobBuilder.*;
36
import static org.quartz.TriggerBuilder.*;
37
import static org.quartz.SimpleScheduleBuilder.*;
38
```
39
40
## Basic Usage
41
42
```java
43
import org.quartz.*;
44
import org.quartz.impl.StdSchedulerFactory;
45
import java.util.Date;
46
47
import static org.quartz.JobBuilder.*;
48
import static org.quartz.TriggerBuilder.*;
49
import static org.quartz.SimpleScheduleBuilder.*;
50
51
// Define a job class
52
public class HelloJob implements Job {
53
public void execute(JobExecutionContext context) throws JobExecutionException {
54
System.out.println("Hello World! - " + new Date());
55
}
56
}
57
58
// Create scheduler instance
59
SchedulerFactory schedFact = new StdSchedulerFactory();
60
Scheduler sched = schedFact.getScheduler();
61
62
// Define job instance
63
JobDetail job = newJob(HelloJob.class)
64
.withIdentity("job1", "group1")
65
.build();
66
67
// Define a trigger that runs every 40 seconds
68
Trigger trigger = newTrigger()
69
.withIdentity("trigger1", "group1")
70
.startNow()
71
.withSchedule(simpleSchedule()
72
.withIntervalInSeconds(40)
73
.repeatForever())
74
.build();
75
76
// Schedule the job with the trigger
77
sched.scheduleJob(job, trigger);
78
79
// Start the scheduler
80
sched.start();
81
```
82
83
## Architecture
84
85
Quartz is built around several key components:
86
87
- **Scheduler**: The main interface for scheduling and managing jobs, acting as the central control point
88
- **Job**: Interface that defines the work to be executed, implemented by application developers
89
- **JobDetail**: Metadata container that describes a job instance including identity, data, and execution properties
90
- **Trigger**: Defines when and how often a job should be executed, with multiple trigger types available
91
- **Builder Pattern**: Fluent API using JobBuilder, TriggerBuilder, and ScheduleBuilder for type-safe object creation
92
- **Listener Framework**: Comprehensive event system for monitoring job executions, trigger firings, and scheduler events
93
- **JobStore**: Persistence layer supporting in-memory (RAMJobStore) or database storage for job and trigger data
94
- **Thread Pool**: Configurable thread management for concurrent job execution
95
96
## Capabilities
97
98
### Core Scheduling
99
100
Primary scheduler management functionality including creating schedulers, lifecycle control, and basic job scheduling operations.
101
102
```java { .api }
103
interface SchedulerFactory {
104
Scheduler getScheduler() throws SchedulerException;
105
Scheduler getScheduler(String schedName) throws SchedulerException;
106
Collection<Scheduler> getAllSchedulers() throws SchedulerException;
107
}
108
109
interface Scheduler {
110
// Lifecycle
111
void start() throws SchedulerException;
112
void startDelayed(int seconds) throws SchedulerException;
113
void standby() throws SchedulerException;
114
void shutdown() throws SchedulerException;
115
void shutdown(boolean waitForJobsToComplete) throws SchedulerException;
116
boolean isStarted() throws SchedulerException;
117
boolean isInStandbyMode() throws SchedulerException;
118
boolean isShutdown() throws SchedulerException;
119
120
// Basic Scheduling
121
Date scheduleJob(JobDetail jobDetail, Trigger trigger) throws SchedulerException;
122
Date scheduleJob(Trigger trigger) throws SchedulerException;
123
void scheduleJobs(Map<JobDetail, Set<? extends Trigger>> triggersAndJobs, boolean replace) throws SchedulerException;
124
}
125
```
126
127
[Core Scheduling](./core-scheduling.md)
128
129
### Job Management
130
131
Job creation, configuration, and lifecycle management including job builders, job data, and execution context.
132
133
```java { .api }
134
interface Job {
135
void execute(JobExecutionContext context) throws JobExecutionException;
136
}
137
138
interface JobDetail {
139
JobKey getKey();
140
String getDescription();
141
Class<? extends Job> getJobClass();
142
JobDataMap getJobDataMap();
143
boolean isDurable();
144
boolean isPersistJobDataAfterExecution();
145
boolean isConcurrentExecutionDisallowed();
146
boolean requestsRecovery();
147
}
148
149
class JobBuilder {
150
static JobBuilder newJob();
151
static JobBuilder newJob(Class<? extends Job> jobClass);
152
JobBuilder withIdentity(String name);
153
JobBuilder withIdentity(String name, String group);
154
JobBuilder withIdentity(JobKey key);
155
JobBuilder withDescription(String jobDescription);
156
JobBuilder ofType(Class<? extends Job> jobClazz);
157
JobBuilder requestRecovery();
158
JobBuilder requestRecovery(boolean jobShouldRecover);
159
JobBuilder storeDurably();
160
JobBuilder storeDurably(boolean jobDurability);
161
JobBuilder usingJobData(String key, String value);
162
JobBuilder usingJobData(JobDataMap newJobDataMap);
163
JobDetail build();
164
}
165
```
166
167
[Job Management](./job-management.md)
168
169
### Trigger Management
170
171
Trigger creation, scheduling control, and various trigger types including simple, cron, and calendar-based triggers.
172
173
```java { .api }
174
interface Trigger {
175
TriggerKey getKey();
176
JobKey getJobKey();
177
String getDescription();
178
String getCalendarName();
179
JobDataMap getJobDataMap();
180
int getPriority();
181
Date getStartTime();
182
Date getEndTime();
183
Date getNextFireTime();
184
Date getPreviousFireTime();
185
Date getFireTimeAfter(Date afterTime);
186
Date getFinalFireTime();
187
int getMisfireInstruction();
188
boolean mayFireAgain();
189
TriggerBuilder<? extends Trigger> getTriggerBuilder();
190
}
191
192
class TriggerBuilder<T extends Trigger> {
193
static TriggerBuilder<Trigger> newTrigger();
194
TriggerBuilder<T> withIdentity(String name);
195
TriggerBuilder<T> withIdentity(String name, String group);
196
TriggerBuilder<T> withIdentity(TriggerKey key);
197
TriggerBuilder<T> withDescription(String triggerDescription);
198
TriggerBuilder<T> withPriority(int triggerPriority);
199
TriggerBuilder<T> modifiedByCalendar(String calName);
200
TriggerBuilder<T> startAt(Date triggerStartTime);
201
TriggerBuilder<T> startNow();
202
TriggerBuilder<T> endAt(Date triggerEndTime);
203
<SBT extends T> TriggerBuilder<SBT> withSchedule(ScheduleBuilder<SBT> schedBuilder);
204
TriggerBuilder<T> forJob(JobKey keyOfJobToFire);
205
TriggerBuilder<T> forJob(String jobName);
206
TriggerBuilder<T> forJob(String jobName, String jobGroup);
207
TriggerBuilder<T> forJob(JobDetail jobDetail);
208
TriggerBuilder<T> usingJobData(String key, String value);
209
TriggerBuilder<T> usingJobData(JobDataMap newJobDataMap);
210
T build();
211
}
212
```
213
214
[Trigger Management](./trigger-management.md)
215
216
### Schedule Builders
217
218
Fluent builders for creating different types of schedules including simple intervals, cron expressions, and calendar-based intervals.
219
220
```java { .api }
221
class SimpleScheduleBuilder extends ScheduleBuilder<SimpleTrigger> {
222
static SimpleScheduleBuilder simpleSchedule();
223
static SimpleScheduleBuilder repeatMinutelyForever();
224
static SimpleScheduleBuilder repeatMinutelyForever(int minutes);
225
static SimpleScheduleBuilder repeatSecondlyForever();
226
static SimpleScheduleBuilder repeatSecondlyForever(int seconds);
227
static SimpleScheduleBuilder repeatHourlyForever();
228
static SimpleScheduleBuilder repeatHourlyForever(int hours);
229
230
SimpleScheduleBuilder withIntervalInMilliseconds(long intervalInMillis);
231
SimpleScheduleBuilder withIntervalInSeconds(int intervalInSeconds);
232
SimpleScheduleBuilder withIntervalInMinutes(int intervalInMinutes);
233
SimpleScheduleBuilder withIntervalInHours(int intervalInHours);
234
SimpleScheduleBuilder withRepeatCount(int triggerRepeatCount);
235
SimpleScheduleBuilder repeatForever();
236
}
237
238
class CronScheduleBuilder extends ScheduleBuilder<CronTrigger> {
239
static CronScheduleBuilder cronSchedule(String cronExpression);
240
static CronScheduleBuilder cronSchedule(CronExpression cronExpression);
241
static CronScheduleBuilder dailyAtHourAndMinute(int hour, int minute);
242
static CronScheduleBuilder weeklyOnDayAndHourAndMinute(int dayOfWeek, int hour, int minute);
243
static CronScheduleBuilder monthlyOnDayAndHourAndMinute(int dayOfMonth, int hour, int minute);
244
245
CronScheduleBuilder inTimeZone(TimeZone timezone);
246
}
247
```
248
249
[Schedule Builders](./schedule-builders.md)
250
251
### Exception Handling
252
253
Comprehensive exception hierarchy for handling scheduling errors, job execution problems, and configuration issues.
254
255
```java { .api }
256
class SchedulerException extends Exception {
257
SchedulerException();
258
SchedulerException(String msg);
259
SchedulerException(Throwable cause);
260
SchedulerException(String msg, Throwable cause);
261
Throwable getUnderlyingException();
262
}
263
264
class JobExecutionException extends SchedulerException {
265
JobExecutionException();
266
JobExecutionException(Throwable cause);
267
JobExecutionException(String msg);
268
JobExecutionException(boolean refireImmediately);
269
JobExecutionException(Throwable cause, boolean refireImmediately);
270
271
void setRefireImmediately(boolean refire);
272
boolean refireImmediately();
273
void setUnscheduleFiringTrigger(boolean unscheduleTriggger);
274
boolean unscheduleFiringTrigger();
275
void setUnscheduleAllTriggers(boolean unscheduleAllTriggers);
276
boolean unscheduleAllTriggers();
277
}
278
```
279
280
[Exception Handling](./exception-handling.md)
281
282
### Listeners and Events
283
284
Event-driven architecture for monitoring job executions, trigger firings, and scheduler lifecycle events.
285
286
```java { .api }
287
interface JobListener {
288
String getName();
289
void jobToBeExecuted(JobExecutionContext context);
290
void jobExecutionVetoed(JobExecutionContext context);
291
void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException);
292
}
293
294
interface TriggerListener {
295
String getName();
296
void triggerFired(Trigger trigger, JobExecutionContext context);
297
boolean vetoJobExecution(Trigger trigger, JobExecutionContext context);
298
void triggerMisfired(Trigger trigger);
299
void triggerComplete(Trigger trigger, JobExecutionContext context, CompletedExecutionInstruction triggerInstructionCode);
300
}
301
302
interface SchedulerListener {
303
void jobScheduled(Trigger trigger);
304
void jobUnscheduled(TriggerKey triggerKey);
305
void triggerFinalized(Trigger trigger);
306
void triggerPaused(TriggerKey triggerKey);
307
void triggersPaused(String triggerGroup);
308
void triggerResumed(TriggerKey triggerKey);
309
void triggersResumed(String triggerGroup);
310
void jobAdded(JobDetail jobDetail);
311
void jobDeleted(JobKey jobKey);
312
void jobPaused(JobKey jobKey);
313
void jobsPaused(String jobGroup);
314
void jobResumed(JobKey jobKey);
315
void jobsResumed(String jobGroup);
316
void schedulerError(String msg, SchedulerException cause);
317
void schedulerInStandbyMode();
318
void schedulerStarted();
319
void schedulerStarting();
320
void schedulerShutdown();
321
void schedulerShuttingdown();
322
void schedulingDataCleared();
323
}
324
```
325
326
[Listeners and Events](./listeners-events.md)
327
328
### Utilities and Helpers
329
330
Utility classes for date manipulation, cron expression parsing, and other common scheduling operations.
331
332
```java { .api }
333
class DateBuilder {
334
enum IntervalUnit {
335
MILLISECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
336
}
337
338
static DateBuilder newDate();
339
static DateBuilder newDateInTimezone(TimeZone tz);
340
static Date todayAt(int hour, int minute, int second);
341
static Date tomorrowAt(int hour, int minute, int second);
342
static Date futureDate(int interval, IntervalUnit unit);
343
static Date nextGivenMinuteDate(Date date, int minuteBase);
344
static Date evenSecondDate(Date date);
345
static Date evenMinuteDate(Date date);
346
static Date evenHourDate(Date date);
347
}
348
349
class CronExpression implements Serializable, Cloneable {
350
CronExpression(String cronExpression) throws ParseException;
351
static boolean isValidExpression(String cronExpression);
352
boolean isSatisfiedBy(Date date);
353
Date getNextValidTimeAfter(Date date);
354
Date getNextInvalidTimeAfter(Date date);
355
TimeZone getTimeZone();
356
void setTimeZone(TimeZone timeZone);
357
String getCronExpression();
358
}
359
```
360
361
[Utilities and Helpers](./utilities-helpers.md)
362
363
### Calendar Management
364
365
Sophisticated time exclusion system for excluding specific dates, times, and periods from trigger schedules using various calendar implementations.
366
367
```java { .api }
368
interface Calendar {
369
boolean isTimeIncluded(long timeStamp);
370
long getNextIncludedTime(long timeStamp);
371
String getDescription();
372
void setDescription(String description);
373
Calendar getBaseCalendar();
374
void setBaseCalendar(Calendar baseCalendar);
375
}
376
377
class HolidayCalendar extends BaseCalendar {
378
void addExcludedDate(Date excludedDate);
379
void removeExcludedDate(Date dateToRemove);
380
SortedSet<Date> getExcludedDates();
381
boolean isDateExcluded(Date dateToCheck);
382
}
383
384
class WeeklyCalendar extends BaseCalendar {
385
void setDayExcluded(int wday, boolean exclude);
386
boolean isDayExcluded(int wday);
387
}
388
```
389
390
[Calendar Management](./calendar-management.md)
391
392
### Matcher Framework
393
394
Advanced pattern matching system for selecting jobs and triggers based on various criteria, enabling powerful bulk operations and complex filtering.
395
396
```java { .api }
397
interface Matcher<T extends Key<T>> {
398
boolean isMatch(T key);
399
}
400
401
class GroupMatcher<T extends Key<T>> implements Matcher<T> {
402
static <T extends Key<T>> GroupMatcher<T> groupEquals(String group);
403
static <T extends Key<T>> GroupMatcher<T> groupStartsWith(String groupPrefix);
404
static <T extends Key<T>> GroupMatcher<T> groupEndsWith(String groupSuffix);
405
static <T extends Key<T>> GroupMatcher<T> groupContains(String groupContains);
406
static GroupMatcher<JobKey> jobGroupEquals(String group);
407
static GroupMatcher<TriggerKey> triggerGroupEquals(String group);
408
}
409
410
class AndMatcher<T extends Key<T>> implements Matcher<T> {
411
static <T extends Key<T>> AndMatcher<T> and(Matcher<T>... matchers);
412
}
413
414
class OrMatcher<T extends Key<T>> implements Matcher<T> {
415
static <T extends Key<T>> OrMatcher<T> or(Matcher<T>... matchers);
416
}
417
```
418
419
[Matcher Framework](./matcher-framework.md)
420
421
### Persistence and Storage
422
423
Comprehensive data persistence system supporting both in-memory and database storage with connection pooling, clustering, and database-specific optimizations.
424
425
```java { .api }
426
interface JobStore {
427
void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException;
428
void storeJob(JobDetail newJob, boolean replaceExisting) throws SchedulerException;
429
void storeTrigger(OperableTrigger newTrigger, boolean replaceExisting) throws SchedulerException;
430
JobDetail retrieveJob(JobKey jobKey) throws SchedulerException;
431
OperableTrigger retrieveTrigger(TriggerKey triggerKey) throws SchedulerException;
432
boolean supportsPersistence();
433
boolean isClustered();
434
}
435
436
class JobStoreTX extends JobStoreSupport {
437
// JDBC job store with transaction management
438
}
439
440
class RAMJobStore implements JobStore {
441
// In-memory job store - volatile storage
442
}
443
444
interface PoolingConnectionProvider extends ConnectionProvider {
445
int getPoolSize();
446
int getMaxPoolSize();
447
int getConnectionsInUse();
448
}
449
```
450
451
[Persistence and Storage](./persistence-storage.md)
452
453
### Enterprise Features
454
455
Enterprise-grade capabilities including JTA transaction support, clustering, JMX monitoring, servlet integration, and specialized job implementations.
456
457
```java { .api }
458
@Target(ElementType.TYPE)
459
@Retention(RetentionPolicy.RUNTIME)
460
@interface ExecuteInJTATransaction {
461
}
462
463
class QuartzInitializerServlet extends HttpServlet {
464
String SHUTDOWN_ON_UNLOAD = "shutdown-on-unload";
465
String START_SCHEDULER_ON_LOAD = "start-scheduler-on-load";
466
void init(ServletConfig cfg) throws ServletException;
467
void destroy();
468
}
469
470
interface SchedulerPlugin {
471
void initialize(String name, Scheduler scheduler) throws SchedulerConfigException;
472
void start();
473
void shutdown();
474
}
475
476
class SendMailJob implements Job {
477
String PROP_SMTP_HOST = "smtp_host";
478
String PROP_RECIPIENT = "recipient";
479
String PROP_SENDER = "sender";
480
String PROP_SUBJECT = "subject";
481
String PROP_MESSAGE = "message";
482
}
483
```
484
485
[Enterprise Features](./enterprise-features.md)
486
487
## Types and Annotations
488
489
### Key Types
490
491
```java { .api }
492
class JobKey extends Key<JobKey> {
493
JobKey(String name);
494
JobKey(String name, String group);
495
static JobKey jobKey(String name);
496
static JobKey jobKey(String name, String group);
497
}
498
499
class TriggerKey extends Key<TriggerKey> {
500
TriggerKey(String name);
501
TriggerKey(String name, String group);
502
static TriggerKey triggerKey(String name);
503
static TriggerKey triggerKey(String name, String group);
504
}
505
506
class JobDataMap extends StringKeyDirtyFlagMap {
507
JobDataMap();
508
JobDataMap(Map<?, ?> map);
509
}
510
```
511
512
### Behavioral Annotations
513
514
```java { .api }
515
@Target(ElementType.TYPE)
516
@Retention(RetentionPolicy.RUNTIME)
517
@interface DisallowConcurrentExecution {
518
}
519
520
@Target(ElementType.TYPE)
521
@Retention(RetentionPolicy.RUNTIME)
522
@interface PersistJobDataAfterExecution {
523
}
524
525
@Target(ElementType.TYPE)
526
@Retention(RetentionPolicy.RUNTIME)
527
@interface ExecuteInJTATransaction {
528
}
529
```
530
531
### Enums and Constants
532
533
```java { .api }
534
enum TriggerState {
535
NONE, NORMAL, PAUSED, COMPLETE, ERROR, BLOCKED
536
}
537
538
enum CompletedExecutionInstruction {
539
NOOP, RE_EXECUTE_JOB, SET_TRIGGER_COMPLETE, DELETE_TRIGGER,
540
SET_ALL_JOB_TRIGGERS_COMPLETE, SET_TRIGGER_ERROR, SET_ALL_JOB_TRIGGERS_ERROR
541
}
542
543
interface Scheduler {
544
String DEFAULT_GROUP = "DEFAULT";
545
String DEFAULT_RECOVERY_GROUP = "RECOVERING_JOBS";
546
String DEFAULT_FAIL_OVER_GROUP = "FAILED_OVER_JOBS";
547
int DEFAULT_PRIORITY = 5;
548
int MISFIRE_INSTRUCTION_SMART_POLICY = 0;
549
int MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY = -1;
550
}
551
```