### Instantiate and Start a Quartz Scheduler
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-01.html
Demonstrates the basic workflow of creating a scheduler instance, starting it, and scheduling a job with a simple trigger.
```java
SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
Scheduler sched = schedFact.getScheduler();
sched.start();
// define the job and tie it to our HelloJob class
JobDetail job = newJob(HelloJob.class)
.withIdentity("myJob", "group1")
.build();
// Trigger the job to run now, and then every 40 seconds
Trigger trigger = newTrigger()
.withIdentity("myTrigger", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger);
```
--------------------------------
### Start and Manage Scheduler Lifecycle
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example3.html
Starts the scheduler, waits for job execution, and performs a graceful shutdown.
```java
sched.start();
```
```java
Thread.sleep(300L * 1000L);
```
```java
sched.shutdown(true);
```
--------------------------------
### Example Console Logging Output
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/quick-start.html
Sample output generated by the Quartz scheduler when no custom logging configuration is provided.
```text
[INFO] 21 Jan 08:46:27.857 AM main [org.quartz.core.QuartzScheduler]
Quartz Scheduler v.2.0.0-SNAPSHOT created.
[INFO] 21 Jan 08:46:27.859 AM main [org.quartz.simpl.RAMJobStore]
RAMJobStore initialized.
[INFO] 21 Jan 08:46:27.865 AM main [org.quartz.core.QuartzScheduler]
Scheduler meta-data: Quartz Scheduler (v2.0.0) 'Scheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 50 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
[INFO] 21 Jan 08:46:27.865 AM main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler 'Scheduler' initialized from default resource file in Quartz package: 'quartz.properties'
[INFO] 21 Jan 08:46:27.866 AM main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler version: 2.0.0
[INFO] 21 Jan 08:46:27.866 AM main [org.quartz.core.QuartzScheduler]
Scheduler Scheduler_$_NON_CLUSTERED started.
[INFO] 21 Jan 08:46:27.866 AM main [org.quartz.core.QuartzScheduler]
Scheduler Scheduler_$_NON_CLUSTERED shutting down.
[INFO] 21 Jan 08:46:27.866 AM main [org.quartz.core.QuartzScheduler]
Scheduler Scheduler_$_NON_CLUSTERED paused.
[INFO] 21 Jan 08:46:27.867 AM main [org.quartz.core.QuartzScheduler]
Scheduler Scheduler_$_NON_CLUSTERED shutdown complete.
```
--------------------------------
### Start Scheduler
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example1.html
Initiate the scheduler to begin processing jobs.
```java
sched.start();
```
--------------------------------
### Define a Quartz-managed DataSource with c3p0
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigDataSources.html
Example configuration for a DataSource named 'myDS' using the c3p0 provider.
```properties
org.quartz.dataSource.myDS.driver = oracle.jdbc.driver.OracleDriver
org.quartz.dataSource.myDS.URL = jdbc:oracle:thin:@10.0.1.23:1521:demodb
org.quartz.dataSource.myDS.user = myUser
org.quartz.dataSource.myDS.password = myPassword
org.quartz.dataSource.myDS.maxConnections = 30
```
--------------------------------
### Start and Shutdown Scheduler
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example4.html
Start the scheduler, wait for jobs to execute, and perform a graceful shutdown.
```java
sched.start();
```
```java
Thread.sleep(60L * 1000L);
```
```java
sched.shutdown(true);
```
--------------------------------
### Cron Expression Examples
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-06.html
Common cron expression patterns for scheduling jobs at specific intervals or times.
```text
0 0/5 * * * ?
```
```text
10 0/5 * * * ?
```
```text
0 30 10-13 ? * WED,FRI
```
```text
0 0/30 8-9 5,20 * ?
```
--------------------------------
### Expected Log Output for Trigger Priorities
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example14.html
Shows the expected console output when running the trigger priority example, demonstrating the firing order based on priority and staggered intervals.
```text
INFO 15 Aug 12:15:51.345 PM PriorityExampleScheduler_Worker-0 org.quartz.examples.example14.TriggerEchoJob
TRIGGER: Priority10Trigger15SecondRepeat
INFO 15 Aug 12:15:51.345 PM PriorityExampleScheduler_Worker-0 org.quartz.examples.example14.TriggerEchoJob
TRIGGER: Priority5Trigger10SecondRepeat
INFO 15 Aug 12:15:51.345 PM PriorityExampleScheduler_Worker-0 org.quartz.examples.example14.TriggerEchoJob
TRIGGER: PriorityNeg5Trigger5SecondRepeat
INFO 15 Aug 12:15:56.220 PM PriorityExampleScheduler_Worker-0 org.quartz.examples.example14.TriggerEchoJob
TRIGGER: PriorityNeg5Trigger5SecondRepeat
INFO 15 Aug 12:16:01.220 PM PriorityExampleScheduler_Worker-0 org.quartz.examples.example14.TriggerEchoJob
TRIGGER: Priority5Trigger10SecondRepeat
INFO 15 Aug 12:16:06.220 PM PriorityExampleScheduler_Worker-0 org.quartz.examples.example14.TriggerEchoJob
TRIGGER: Priority10Trigger15SecondRepeat
```
--------------------------------
### Static Imports for Quartz DSL
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook
Essential static imports for accessing Quartz's DSL classes, required for the examples in this cookbook.
```java
import static org.quartz.JobBuilder.*;
import static org.quartz.TriggerBuilder.*;
import static org.quartz.SimpleScheduleBuilder.*;
import static org.quartz.CronScheduleBuilder.*;
import static org.quartz.CalendarIntervalScheduleBuilder.*;
import static org.quartz.JobKey.*;
import static org.quartz.TriggerKey.*;
import static org.quartz.DateBuilder.*;
import static org.quartz.impl.matchers.KeyMatcher.*;
import static org.quartz.impl.matchers.GroupMatcher.*;
import static org.quartz.impl.matchers.AndMatcher.*;
import static org.quartz.impl.matchers.OrMatcher.*;
import static org.quartz.impl.matchers.EverythingMatcher.*;
```
--------------------------------
### Build a trigger that will fire once, five minutes in the future
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-05.html
Uses DateBuilder to calculate a start time relative to the current time.
```java
trigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger5", "group1")
.startAt(futureDate(5, IntervalUnit.MINUTE)) // use DateBuilder to create a date in the future
.forJob(myJobKey) // identify job with its JobKey
.build();
```
--------------------------------
### Build a trigger for a specific moment in time, then repeating every ten seconds ten times
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-05.html
Configures a trigger to fire at a start time followed by 10 repeats, resulting in 11 total firings.
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startAt(myTimeToStartFiring) // if a start time is not given (if this line were omitted), "now" is implied
.withSchedule(simpleSchedule()
.withIntervalInSeconds(10)
.withRepeatCount(10)) // note that 10 repeats will give a total of 11 firings
.forJob(myJob) // identify job with handle to its JobDetail itself
.build();
```
--------------------------------
### Initialize and Shutdown Scheduler in Java
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/quick-start.html
Obtains a scheduler instance from the factory, starts it, and shuts it down. The application will remain active until shutdown is called due to internal threads.
```java
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.JobBuilder.*;
import static org.quartz.TriggerBuilder.*;
import static org.quartz.SimpleScheduleBuilder.*;
public class QuartzTest {
public static void main(String[] args) {
try {
// Grab the Scheduler instance from the Factory
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// and start it off
scheduler.start();
scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
}
}
}
```
--------------------------------
### Create a Ten-Second SimpleTrigger
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/TenSecTrigger.html
Use this configuration to define a trigger that starts immediately and repeats indefinitely every ten seconds.
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(10)
.repeatForever())
.build();
```
--------------------------------
### Create Triggers with Different Priorities
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example14.html
Defines three triggers with varying priorities and start times to demonstrate priority-based scheduling.
```java
// Calculate the start time of all triggers as 5 seconds from now
Date startTime = futureDate(5, IntervalUnit.SECOND);
// First trigger has priority of 1, and will repeat after 5 seconds
Trigger trigger1 = newTrigger()
.withIdentity("PriorityNeg5Trigger5SecondRepeat")
.startAt(startTime)
.withSchedule(simpleSchedule().withRepeatCount(1).withIntervalInSeconds(5))
.withPriority(1)
.forJob(job)
.build();
// Second trigger has default priority of 5 (default), and will repeat after 10 seconds
Trigger trigger2 = newTrigger()
.withIdentity("Priority5Trigger10SecondRepeat")
.startAt(startTime)
.withSchedule(simpleSchedule().withRepeatCount(1).withIntervalInSeconds(10))
.forJob(job)
.build();
// Third trigger has priority 10, and will repeat after 15 secondsTrigger trigger3 = newTrigger()
.withIdentity("Priority10Trigger15SecondRepeat")
.startAt(startTime)
.withSchedule(simpleSchedule().withRepeatCount(1).withIntervalInSeconds(15))
.withPriority(10)
.forJob(job)
.build();
```
--------------------------------
### Configure Quartz via Startup Servlet in web.xml
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/ServletInitScheduler.html
Use the QuartzInitializerServlet with a load-on-startup priority to initialize the scheduler.
```xml
...
QuartzInitializer
org.quartz.ee.servlet.QuartzInitializerServlet
shutdown-on-unload
true
2
...
```
--------------------------------
### Instantiate a Scheduler from a Property File
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/CreateScheduler.html
Initializes the factory by providing the path to a specific configuration file.
```java
StdSchedulerFactory sf = new StdSchedulerFactory();
sf.initialize(fileName);
Scheduler scheduler = sf.getScheduler();
// Scheduler will not execute jobs until it has been started (though they can be scheduled before start())
scheduler.start();
```
--------------------------------
### Toggle Scheduler Standby Mode
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/SchedulerStandby.html
Use standby to pause execution and start to resume it. Ensure start has been called previously before invoking standby.
```java
// start() was previously invoked on the scheduler
scheduler.standby();
// now the scheduler will not fire triggers / execute jobs
// ...
scheduler.start();
// now the scheduler will fire triggers and execute jobs
```
--------------------------------
### Configure DriverDelegate Initialization String
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigJobStoreTX.html
Format for defining initialization properties for the DriverDelegate using a pipe-delimited string.
```text
"settingName=settingValue|otherSettingName=otherSettingValue|..."
```
--------------------------------
### Configure Quartz via Context Listener in web.xml
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/ServletInitScheduler.html
Use the QuartzInitializerListener to initialize the scheduler. Configuration parameters are defined as context-param entries.
```xml
...
quartz:config-file
/some/path/my_quartz.properties
quartz:shutdown-on-unload
true
quartz:wait-on-shutdown
false
quartz:start-scheduler-on-load
true
...
org.quartz.ee.servlet.QuartzInitializerListener
...
```
--------------------------------
### Build a trigger for a specific moment in time, with no repeats
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-05.html
Creates a trigger that fires exactly once at a specified start time.
```java
SimpleTrigger trigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger1", "group1")
.startAt(myStartTime) // some Date
.forJob("job1", "group1") // identify job with name, group strings
.build();
```
--------------------------------
### Import static matchers
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-07.html
Static imports for matcher and key classes to simplify listener registration code.
```java
import static org.quartz.JobKey.*;
import static org.quartz.impl.matchers.KeyMatcher.*;
import static org.quartz.impl.matchers.GroupMatcher.*;
import static org.quartz.impl.matchers.AndMatcher.*;
import static org.quartz.impl.matchers.OrMatcher.*;
import static org.quartz.impl.matchers.EverythingMatcher.*;
...etc.
```
--------------------------------
### General Plugin Configuration Pattern
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigPlugins.html
The standard format for defining any Quartz plugin in the configuration file.
```properties
org.quartz.plugin.NAME.class = com.foo.MyPluginClass
org.quartz.plugin.NAME.propName = propValue
org.quartz.plugin.NAME.prop2Name = prop2Value
```
--------------------------------
### Quartz JDBC-JobStore Clustering Configuration
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigJDBCJobStoreClustering.html
Properties file configuration for enabling clustering, defining the JobStore, and setting up the data source.
```properties
#============================================================================
# Configure Main Scheduler Properties
#============================================================================
org.quartz.scheduler.instanceName = MyClusteredScheduler
org.quartz.scheduler.instanceId = AUTO
#============================================================================
# Configure ThreadPool
#============================================================================
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 25
org.quartz.threadPool.threadPriority = 5
#============================================================================
# Configure JobStore
#============================================================================
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.oracle.OracleDelegate
org.quartz.jobStore.useProperties = false
org.quartz.jobStore.dataSource = myDS
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.isClustered = true
org.quartz.jobStore.clusterCheckinInterval = 20000
#============================================================================
# Configure Datasources
#============================================================================
org.quartz.dataSource.myDS.driver = oracle.jdbc.driver.OracleDriver
org.quartz.dataSource.myDS.URL = jdbc:oracle:thin:@polarbear:1521:dev
org.quartz.dataSource.myDS.user = quartz
org.quartz.dataSource.myDS.password = quartz
org.quartz.dataSource.myDS.maxConnections = 5
org.quartz.dataSource.myDS.validationQuery=select 0 from dual
```
--------------------------------
### Basic quartz.properties configuration
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/quick-start.html
A minimal configuration file defining the scheduler instance name, thread pool size, and in-memory job storage.
```properties
org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 3
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
```
--------------------------------
### Instantiate the Default Scheduler
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/CreateScheduler.html
Uses the default quartz.properties file found in the classpath or working directory.
```java
// the 'default' scheduler is defined in "quartz.properties" found
// in the current working directory, in the classpath, or
// resorts to a fall-back default that is in the quartz.jar
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
// Scheduler will not execute jobs until it has been started (though they can be scheduled before start())
scheduler.start();
```
--------------------------------
### Instantiate a Scheduler from Specific Properties
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/CreateScheduler.html
Initializes the factory with a custom properties object before retrieving the scheduler.
```java
StdSchedulerFactory sf = new StdSchedulerFactory();
sf.initialize(schedulerProperties);
Scheduler scheduler = sf.getScheduler();
// Scheduler will not execute jobs until it has been started (though they can be scheduled before start())
scheduler.start();
```
--------------------------------
### Initialize Scheduler with Properties
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example14.html
Configures a StdSchedulerFactory using a specific properties file to create a RAM-based scheduler instance.
```java
SchedulerFactory sf = new StdSchedulerFactory(
"org/quartz/examples/example14/quartz_priority.properties");
Scheduler sched = sf.getScheduler();
```
--------------------------------
### Implementing a Basic Job Class
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-03.html
A standard Job implementation requiring a no-argument constructor for the default JobFactory.
```java
public class HelloJob implements Job {
public HelloJob() {
}
public void execute(JobExecutionContext context)
throws JobExecutionException
{
System.err.println("Hello! HelloJob is executing.");
}
}
```
--------------------------------
### Defining and Scheduling a Job
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-03.html
Demonstrates creating a JobDetail and a Trigger, then scheduling them with the scheduler instance.
```java
// define the job and tie it to our HelloJob class
JobDetail job = newJob(HelloJob.class)
.withIdentity("myJob", "group1") // name "myJob", group "group1"
.build();
// Trigger the job to run now, and then every 40 seconds
Trigger trigger = newTrigger()
.withIdentity("myTrigger", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger);
```
--------------------------------
### Configure a Global JobListener
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigListeners.html
Define a global JobListener by specifying the class name and any required properties in the configuration file.
```properties
org.quartz.jobListener.NAME.class = com.foo.MyListenerClass
org.quartz.jobListener.NAME.propName = propValue
org.quartz.jobListener.NAME.prop2Name = prop2Value
```
--------------------------------
### Implement HelloJob
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example1.html
A simple job implementation that logs a message to the console with the current timestamp.
```java
public void execute(JobExecutionContext context) throws JobExecutionException {
// Say Hello to the World and display the date/time
_log.info("Hello World! - " + new Date());
}
```
--------------------------------
### Configure TerracottaJobStore
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-09.html
Sets the JobStore class to TerracottaJobStore and defines the connection URL for the Terracotta server.
```properties
org.quartz.jobStore.class = org.terracotta.quartz.TerracottaJobStore
org.quartz.jobStore.tcConfigUrl = localhost:9510
```
--------------------------------
### Initialize Scheduler
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example1.html
Create a RAM-based scheduler instance using the StdSchedulerFactory.
```java
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
```
--------------------------------
### Create SimpleTrigger
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example1.html
Configure a trigger to fire at the next round minute.
```java
// compute a time that is on the next round minute
Date runTime = evenMinuteDate(new Date());
// Trigger the job to run on the next round minute
Trigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.startAt(runTime)
.build();
```
--------------------------------
### Create Database Indexes for Quartz Tables
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/faq.html
Manually add these indexes to your database to optimize query performance for the trigger and fired trigger tables.
```sql
create index idx_qrtz_t_next_fire_time on qrtz_triggers(NEXT_FIRE_TIME);
create index idx_qrtz_t_state on qrtz_triggers(TRIGGER_STATE);
create index idx_qrtz_t_nf_st on qrtz_triggers(TRIGGER_STATE,NEXT_FIRE_TIME);
create index idx_qrtz_ft_trig_name on qrtz_fired_triggers(TRIGGER_NAME);
create index idx_qrtz_ft_trig_group on qrtz_fired_triggers(TRIGGER_GROUP);
create index idx_qrtz_ft_trig_name on qrtz_fired_triggers(TRIGGER_NAME);
create index idx_qrtz_ft_trig_n_g on \
qrtz_fired_triggers(TRIGGER_NAME,TRIGGER_GROUP);
create index idx_qrtz_ft_trig_inst_name on qrtz_fired_triggers(INSTANCE_NAME);
create index idx_qrtz_ft_job_name on qrtz_fired_triggers(JOB_NAME);
create index idx_qrtz_ft_job_group on qrtz_fired_triggers(JOB_GROUP);
create index idx_qrtz_t_next_fire_time_misfire on \
qrtz_triggers(MISFIRE_INSTR,NEXT_FIRE_TIME);
create index idx_qrtz_t_nf_st_misfire on \
qrtz_triggers(MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE);
create index idx_qrtz_t_nf_st_misfire_grp on \
qrtz_triggers(MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE);
```
--------------------------------
### Configure XMLSchedulingDataProcessorPlugin in quartz.properties
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/JobInitPlugin.html
Define the plugin class and file settings within the Quartz properties file to enable XML-based job initialization.
```properties
#===================================================
# Configure the Job Initialization Plugin
#===================================================
org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
org.quartz.plugin.jobInitializer.fileNames = jobs.xml
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
org.quartz.plugin.jobInitializer.scanInterval = 10
org.quartz.plugin.jobInitializer.wrapInUserTransaction = false
```
--------------------------------
### Schedule a Job with Quartz
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/ScheduleJob.html
Defines a job instance and a trigger that fires immediately, then registers both with the scheduler.
```java
// Define job instance
JobDetail job1 = newJob(ColorJob.class)
.withIdentity("job1", "group1")
.build();
// Define a Trigger that will fire "now", and not repeat
Trigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.build();
// Schedule the job with the trigger
sched.scheduleJob(job, trigger);
```
--------------------------------
### Setting The Scheduler’s JobStore to JobStoreTX
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigJobStoreTX.html
Configure the scheduler to use the JobStoreTX implementation by setting the class property in the configuration file.
```properties
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
```
--------------------------------
### Implement Custom ConnectionProvider
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigDataSources.html
Specifies a custom class for connection management and provides additional bean-style properties.
```properties
org.quartz.dataSource.myCustomDS.connectionProvider.class = com.foo.FooConnectionProvider
org.quartz.dataSource.myCustomDS.someStringProperty = someValue
org.quartz.dataSource.myCustomDS.someIntProperty = 5
```
--------------------------------
### Static Imports for Quartz DSL
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-02.html
Required static imports to enable the fluent builder DSL methods for jobs, triggers, and schedules.
```java
import static org.quartz.JobBuilder.*;
import static org.quartz.SimpleScheduleBuilder.*;
import static org.quartz.CronScheduleBuilder.*;
import static org.quartz.CalendarIntervalScheduleBuilder.*;
import static org.quartz.TriggerBuilder.*;
import static org.quartz.DateBuilder.*;
```
--------------------------------
### Define and Schedule a Job with Quartz DSL
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-02.html
Uses JobBuilder and TriggerBuilder to define a job instance and its execution schedule, then registers it with the scheduler.
```java
// define the job and tie it to our HelloJob class
JobDetail job = newJob(HelloJob.class)
.withIdentity("myJob", "group1") // name "myJob", group "group1"
.build();
// Trigger the job to run now, and then every 40 seconds
Trigger trigger = newTrigger()
.withIdentity("myTrigger", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger);
```
--------------------------------
### Static Import for JobBuilder
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-03.html
Use this static import to enable the DSL-style syntax when building JobDetail instances.
```java
import static org.quartz.JobBuilder.*;
```
--------------------------------
### Build a trigger that will fire now, then repeat every five minutes, until the hour 22:00
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-05.html
Demonstrates using an end time to override the repeat count for a recurring schedule.
```java
trigger = newTrigger()
.withIdentity("trigger7", "group1")
.withSchedule(simpleSchedule()
.withIntervalInMinutes(5)
.repeatForever())
.endAt(dateOf(22, 0, 0))
.build();
```
--------------------------------
### Configure HikariCP DataSource
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigDataSources.html
Defines a Quartz-managed DataSource using HikariCP with specific driver, URL, and pool settings.
```properties
org.quartz.dataSource.myDS.driver = hikaricp
org.quartz.dataSource.myDS.driver = oracle.jdbc.driver.OracleDriver
org.quartz.dataSource.myDS.URL = jdbc:oracle:thin:@10.0.1.23:1521:demodb
org.quartz.dataSource.myDS.user = myUser
org.quartz.dataSource.myDS.password = myPassword
org.quartz.dataSource.myDS.maximumPoolSize = 30
org.quartz.dataSource.myDS.connectionTestQuery = SELECT 1
org.quartz.dataSource.myDS.idleTimeout = 0
```
--------------------------------
### Configure 90-minute interval with SimpleTrigger
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/NinetyMinTrigger.html
Use SimpleTrigger for fixed-interval scheduling where the interval is defined in minutes.
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInMinutes(90)
.repeatForever())
.build();
```
--------------------------------
### Configure a Global TriggerListener
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigListeners.html
Define a global TriggerListener by specifying the class name and any required properties in the configuration file.
```properties
org.quartz.triggerListener.NAME.class = com.foo.MyListenerClass
org.quartz.triggerListener.NAME.propName = propValue
org.quartz.triggerListener.NAME.prop2Name = prop2Value
```
--------------------------------
### Configure quartz_priority.properties
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example14.html
Properties file configuration to set the thread count to 1, ensuring that trigger priorities act as the tie-breaker for concurrent jobs.
```properties
org.quartz.scheduler.instanceName=PriorityExampleScheduler
# Set thread count to 1 to force Triggers scheduled for the same time to
# to be ordered by priority.
org.quartz.threadPool.threadCount=1
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore
```
--------------------------------
### Register a JobListener using static imports
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-07.html
Registers a listener using static imports for cleaner syntax.
```java
scheduler.getListenerManager().addJobListener(myJobListener, jobKeyEquals(jobKey("myJobName", "myJobGroup")));
```
--------------------------------
### Configure JobDataMap Parameters
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example4.html
Set initial values for job parameters in the JobDataMap before scheduling.
```java
job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");
job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
```
```java
job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");
job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
```
--------------------------------
### Implement a Job class with JobDataMap access
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/DefineJobWithData.html
Create a class implementing the Job interface, ensuring a public no-argument constructor exists for the scheduler to instantiate it.
```java
public class PrintPropsJob implements Job {
public PrintPropsJob() {
// Instances of Job must have a public no-argument constructor.
}
public void execute(JobExecutionContext context)
throws JobExecutionException {
JobDataMap data = context.getMergedJobDataMap();
System.out.println("someProp = " + data.getString("someProp"));
}
}
```
--------------------------------
### Set the Scheduler JobStore to JobStoreCMT
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigJobStoreCMT.html
Configure the Quartz scheduler to use the JobStoreCMT implementation by setting the class property.
```properties
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreCMT
```
--------------------------------
### Implement JobListener Interface
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/JobListeners.html
Create a custom listener by implementing the full JobListener interface, which requires defining all event handler methods.
```java
package foo;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
public class MyJobListener implements JobListener {
private String name;
public MyJobListener(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void jobToBeExecuted(JobExecutionContext context) {
// do something with the event
}
public void jobWasExecuted(JobExecutionContext context,
JobExecutionException jobException) {
// do something with the event
}
public void jobExecutionVetoed(JobExecutionContext context) {
// do something with the event
}
}
```
--------------------------------
### Configure XML Scheduling Data Processor Plugin
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigPlugins.html
Configures the XMLSchedulingDataProcessorPlugin to load job and trigger definitions from an XML file during initialization.
```properties
org.quartz.plugin.jobInitializer.class = \
org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
org.quartz.plugin.jobInitializer.fileNames = \
data/my_job_data.xml
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
```
--------------------------------
### Configure Bi-Weekly Execution with SimpleTrigger
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/BiWeeklyTrigger.html
Uses a SimpleTrigger with an interval of 14 days in hours. Note that this may be affected by daylight savings time shifts.
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startAt(tomorrowAt(15, 0, 0) // first fire time 15:00:00 tomorrow
.withSchedule(simpleSchedule()
.withIntervalInHours(14 * 24) // interval is actually set at 14 * 24 hours' worth of milliseconds
.repeatForever())
.build();
```
--------------------------------
### Configure DriverDelegate
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-09.html
Specify the DriverDelegate class to handle database-specific JDBC operations.
```properties
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
```
--------------------------------
### Configure Table Prefix
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-09.html
Define the prefix used for Quartz database tables.
```properties
org.quartz.jobStore.tablePrefix = QRTZ_
```
--------------------------------
### Define jobs and triggers in jobs.xml
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/JobInitPlugin.html
Use the job-scheduling-data schema to declaratively define jobs, triggers, and associated data maps.
```xml
my-very-clever-job
MYJOB_GROUP
The job description
com.acme.scheduler.job.CleverJob
burger-type
hotdog
dressing-list
ketchup,mayo
my-trigger
MYTRIGGER_GROUP
my-very-clever-job
MYJOB_GROUP
0 30 4 * * ?
```
--------------------------------
### Register and Apply a HolidayCalendar
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-04.html
Instantiate a HolidayCalendar, add excluded dates, and associate it with multiple triggers to skip job execution on specific days.
```java
HolidayCalendar cal = new HolidayCalendar();
cal.addExcludedDate( someDate );
cal.addExcludedDate( someOtherDate );
sched.addCalendar("myHolidays", cal, false);
Trigger t = newTrigger()
.withIdentity("myTrigger")
.forJob("myJob")
.withSchedule(dailyAtHourAndMinute(9, 30)) // execute job daily at 9:30
.modifiedByCalendar("myHolidays") // but not on holidays
.build();
// .. schedule job with trigger
Trigger t2 = newTrigger()
.withIdentity("myTrigger2")
.forJob("myJob2")
.withSchedule(dailyAtHourAndMinute(11, 30)) // execute job daily at 11:30
.modifiedByCalendar("myHolidays") // but not on holidays
.build();
// .. schedule job with trigger2
```
--------------------------------
### Implement TriggerListener Interface
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/TriggerListeners.html
Create a custom listener by implementing the TriggerListener interface and defining the required event methods.
```java
package foo;
import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.quartz.TriggerListener;
import org.quartz.Trigger.CompletedExecutionInstruction;
public class MyTriggerListener implements TriggerListener {
private String name;
public MyTriggerListener(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void triggerComplete(Trigger trigger, JobExecutionContext context,
CompletedExecutionInstruction triggerInstructionCode) {
// do something with the event
}
public void triggerFired(Trigger trigger, JobExecutionContext context) {
// do something with the event
}
public void triggerMisfired(Trigger trigger) {
// do something with the event
}
public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) {
// do something with the event
return false;
}
}
```
--------------------------------
### Configure Custom ThreadPool Properties
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigThreadPool.html
Use this pattern to set custom properties on a user-defined ThreadPool implementation via reflection.
```properties
org.quartz.threadPool.class = com.mycompany.goo.FooThreadPool
org.quartz.threadPool.somePropOfFooThreadPool = someValue
```
--------------------------------
### Configure Weekly SimpleTrigger
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/WeeklyTrigger.html
Uses SimpleTrigger with a fixed interval of 7 days. Note that this may drift due to daylight savings time changes.
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startAt(tomorrowAt(15, 0, 0) // first fire time 15:00:00 tomorrow
.withSchedule(simpleSchedule()
.withIntervalInHours(7 * 24) // interval is actually set at 7 * 24 hours' worth of milliseconds
.repeatForever())
.build();
```
--------------------------------
### Configure JDBCJobStore DataSource
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-09.html
Specifies the named DataSource to be used by the JDBCJobStore in Quartz properties.
```properties
org.quartz.jobStore.dataSource = myDS
```
--------------------------------
### Implement TriggerEchoJob
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example14.html
A simple job implementation that logs the key of the trigger that initiated the execution.
```java
public void execute(JobExecutionContext context) throws JobExecutionException {
LOG.info("TRIGGER: " + context.getTrigger().getKey());
}
```
--------------------------------
### Implement the Job Interface
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/tutorials/tutorial-lesson-02.html
The Job interface requires a single execute method to be implemented for task execution.
```java
package org.quartz;
public interface Job {
public void execute(JobExecutionContext context)
throws JobExecutionException;
}
```
--------------------------------
### Configure Monthly CronTriggers
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/MonthlyTrigger.html
Various CronTrigger configurations for monthly execution, including specific days, the last day, the last weekday, and offsets from the end of the month.
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startNow()
.withSchedule(monthlyOnDayAndHourAndMinute(5, 15, 0)) // fire on the 5th day of every month at 15:00
.build();
```
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startNow()
.withSchedule(cronSchedule("0 0 15 5 * ?")) // fire on the 5th day of every month at 15:00
.build();
```
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startNow()
.withSchedule(cronSchedule("0 0 15 L * ?")) // fire on the last day of every month at 15:00
.build();
```
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startNow()
.withSchedule(cronSchedule("0 0 15 LW * ?")) // fire on the last weekday day of every month at 15:00
.build();
```
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startNow()
.withSchedule(cronSchedule("0 0 15 L-3 * ?")) // fire on the third to last day of every month at 15:00
.build();
```
--------------------------------
### Log Job Execution Details
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example4.html
Log the job key, execution time, favorite color, and execution counts from both the JobDataMap and a member variable.
```java
_log.info("ColorJob: " + jobKey + " executing at " + new Date() + "\n" +
" favorite color is " + favoriteColor + "\n" +
" execution count (from job map) is " + count + "\n" +
" execution count (from job member variable) is " + _counter);
```
--------------------------------
### Configure Connection Validation Query
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/faq.html
Specify a validation query in your quartz.properties file to ensure Quartz can recover database connections after a server restart.
```properties
org.quartz.dataSource.myDS.validationQuery=select 0 from dual
```
--------------------------------
### Define and Schedule a Job
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/quick-start.html
Creates a JobDetail and a Trigger to schedule a job for execution. Requires the scheduler to be running and sufficient time for execution before shutdown.
```java
// define the job and tie it to our HelloJob class
JobDetail job = newJob(HelloJob.class)
.withIdentity("job1", "group1")
.build();
// Trigger the job to run now, and then repeat every 40 seconds
Trigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
// Tell quartz to schedule the job using our trigger
scheduler.scheduleJob(job, trigger);
```
--------------------------------
### Implement SimpleJob execution logic
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/examples/Example3.html
Defines the job execution logic by implementing the Job interface and logging the current execution time.
```java
public void execute(JobExecutionContext context) throws JobExecutionException {
JobKey jobKey = context.getJobDetail().getKey();
_log.info("SimpleJob says: " + jobKey + " executing at " + new Date());
}
```
--------------------------------
### Enable Bulk Retrieval Statements
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/faq.html
Add this property to your quartz.properties file to enable bulk retrieval statements for improved performance.
```properties
org.quartz.jobStore.useEnhancedStatements=true
```
--------------------------------
### Set Scheduler JobStore to RAMJobStore
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigRAMJobStore.html
Configures the Quartz scheduler to use the in-memory RAMJobStore implementation.
```properties
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
```
--------------------------------
### Create a custom SchedulerListener
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/SchedulerListeners.html
Extend the SchedulerListenerSupport class and override specific event methods to handle scheduler lifecycle events.
```java
package foo;
import org.quartz.Trigger;
import org.quartz.listeners.SchedulerListenerSupport;
public class MyOtherSchedulerListener extends SchedulerListenerSupport {
@Override
public void schedulerStarted() {
// do something with the event
}
@Override
public void schedulerShutdown() {
// do something with the event
}
@Override
public void jobScheduled(Trigger trigger) {
// do something with the event
}
}
```
--------------------------------
### Create a daily CronTrigger
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/cookbook/DailyTrigger.html
Use CronTrigger to ensure the fire time remains consistent across daylight savings time changes.
```java
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startNow()
.withSchedule(dailyAtHourAndMinute(15, 0)) // fire every day at 15:00
.build();
```
--------------------------------
### Reference Application Server DataSource
Source: https://www.quartz-scheduler.org/documentation/quartz-2.5.x/configuration/ConfigDataSources.html
Configures a JNDI-based DataSource lookup for connections managed by an application server.
```properties
org.quartz.dataSource.myOtherDS.jndiURL=jdbc/myDataSource
org.quartz.dataSource.myOtherDS.java.naming.factory.initial=com.evermind.server.rmi.RMIInitialContextFactory
org.quartz.dataSource.myOtherDS.java.naming.provider.url=ormi://localhost
org.quartz.dataSource.myOtherDS.java.naming.security.principal=admin
org.quartz.dataSource.myOtherDS.java.naming.security.credentials=123
```