Introduction
Quartz is a powerful scheduling library that can be used to perform timing tasks in Java applications. Quartz is relatively simple to configure and use in a stand-alone environment, but in distributed systems, Quartz is usually configured in cluster mode to ensure uniqueness and high availability of tasks. This article will explain how to configure a Quartz cluster under the Spring framework and use MySQL as the data source to store scheduling information.
Environmental preparation
- Java Version: 1.8 or higher
- Spring Boot Version: 2.
- Quartz version: 2.
- database: MySQL 5.7 or higher
Step 1: Add dependencies
First, in
Add Spring Boot and Quartz dependencies to the file:
<dependencies> <!-- Spring Boot Starter --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- Quartz Scheduler --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- Spring Boot Starter Data JPA --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies>
Step 2: Configure the database
In
Configure database connections in :
=jdbc:mysql://localhost:3306/quartz?useSSL=false&serverTimezone=UTC =root =root -class-name= -auto=update -sql=true
Step 3: Create Quartz table
Quartz requires some specific tables to store scheduling information. These tables can be created using SQL scripts provided by Quartz. For MySQL, you can use the tables_mysql_innodb.sql script.
Execute SQL statements from the script to the MySQL database:
-- Example:create Quartz surface CREATE TABLE QRTZ_JOB_DETAILS( SCHED_NAME VARCHAR(120) NOT NULL, JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, DESCRIPTION VARCHAR(250) NULL, JOB_CLASS_NAME VARCHAR(250) NOT NULL, IS_DURABLE VARCHAR(1) NOT NULL, IS_NONCONCURRENT VARCHAR(1) NOT NULL, IS_UPDATE_DATA VARCHAR(1) NOT NULL, REQUESTS_RECOVERY VARCHAR(1) NOT NULL, JOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP) ) ENGINE=InnoDB; -- 其他surfacecreate语句...
Step 4: Configure Quartz cluster
In
Configure Quartz in to enable cluster mode:
# Quartz Configuration-store-type=jdbc -schema=always =ClusteredScheduler =AUTO = =true =20000 =60000 =QRTZ_
Step 5: Create a task
Define a simple Quartz task class:
import ; import ; import ; public class SimpleJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { ("SimpleJob is running..."); } }
Step 6: Configure task scheduling
Configure task scheduling in the Spring configuration class:
import ; import ; import ; import ; import ; import ; import ; import ; @Configuration public class QuartzConfig { @Bean public JobDetailFactoryBean jobDetail() { JobDetailFactoryBean factoryBean = new JobDetailFactoryBean(); (); (true); return factoryBean; } @Bean public SimpleTriggerFactoryBean trigger(JobDetail jobDetail) { SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean(); (jobDetail); (10000); // Execute every 10 seconds (SimpleTrigger.REPEAT_INDEFINITELY); (0L); (SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT); return factoryBean; } }
Step 7: Start the application
Start the Spring Boot application, Quartz will automatically run in cluster mode, and all nodes will share the same scheduling information.
Spring Quartz is a very popular scheduling framework for performing timed tasks in Java applications. When using Quartz and Spring framework, cluster deployment can be achieved by configuring MySQL as a data source, ensuring high availability and load balancing.
Here is a simple example showing how to configure and use Spring Quartz clusters (using MySQL as the data source) in a Spring Boot project:
1. Add dependencies
First, add Spring Boot, Quartz, and MySQL dependencies to the file:
<dependencies> <!-- Spring Boot Starter --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- Spring Boot Starter Web --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Quartz Scheduler --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- HikariCP Connection Pool --> <dependency> <groupId></groupId> <artifactId>HikariCP</artifactId> </dependency> </dependencies>
2. Configure MySQL data source
In
or
Configure the MySQL data source and the related properties of Quartz in :
# Data source configuration=jdbc:mysql://localhost:3306/quartz_db?useSSL=false&serverTimezone=UTC =root =password -class-name= # HikariCP connection pool configuration-name=HikariCP -pool-size=10 # Quartz configuration-store-type=jdbc = = =QRTZ_ =true =20000 =ClusteredScheduler =AUTO
3. Create Quartz Job
Create a simple Quartz Job class that implementsJob
Interface:
import ; import ; import ; import org.; import org.; public class MyJob implements Job { private static final Logger logger = (); @Override public void execute(JobExecutionContext context) throws JobExecutionException { ("Executing job at: " + new ()); } }
4. Configure Quartz Job and Trigger
Define Quartz Job and Trigger in Spring Boot configuration class:
import ; import ; import ; import ; import ; import ; import ; @Configuration public class QuartzConfig { @Bean public JobDetailFactoryBean jobDetail() { JobDetailFactoryBean factoryBean = new JobDetailFactoryBean(); (); (true); return factoryBean; } @Bean public SimpleTriggerFactoryBean trigger(JobDetail jobDetail) { SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean(); (jobDetail); (10000); // Execute every 10 seconds (SimpleTrigger.REPEAT_INDEFINITELY); (0); (SimpleScheduleBuilder.MISFIRE_INSTRUCTION_FIRE_NOW); return factoryBean; } }
5. Start the Spring Boot application
Finally, create a Spring Boot startup class:
import ; import ; @SpringBootApplication public class QuartzClusterApplication { public static void main(String[] args) { (, args); } }
6. Initialize the Quartz table
Make sure to create the tables required by Quartz in the MySQL database. You can use SQL scripts provided by Quartz, usually located in Quartz's distribution package, or downloaded from Quartz's GitHub repository.
For example, create a table with the following command:
CREATE DATABASE quartz_db; USE quartz_db; -- runQuartzProvidedSQLscript SOURCE path/to/tables_mysql_innodb.sql;
7. Test
Start multiple instances (each runs on a different port), observe log output, and ensure tasks are executed alternately on different nodes in the cluster.
The above is a complete Spring Boot + Quartz + MySQL cluster configuration example. Hope it helps you! If you have any questions or need further assistance, feel free to let me know. In cluster environments that use Spring and Quartz to build timing tasks, MySQL is often used as a persistent storage to ensure that the scheduling information of the task can be shared among different nodes in the cluster. This can prevent the same task from being executed repeatedly on multiple nodes, and can ensure that even if a node goes down, other nodes can take over unfinished tasks.
Here is a detailed step and sample code that describes how to configure and use a Quartz cluster (MySQL data source) in a Spring Boot project:
1. Add dependencies
First, in
Add Spring Boot and Quartz related dependencies to the file:
<dependencies> <!-- Spring Boot Starter --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- Quartz --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- Spring Boot Starter Data JPA --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies>
2. Configure Quartz
In
or
Configure Quartz to connect to MySQL database:
# MySQL database configuration=jdbc:mysql://localhost:3306/quartz?useSSL=false&serverTimezone=UTC =root =password -class-name= # Quartz Configuration-store-type=jdbc -schema=always =ClusteredScheduler =AUTO = =true =20000 =60000 =QRTZ_ = =10
3. Create a timed task
Create a simple timed task class:
import ; import ; import ; public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { ("MyJob is running on node " + ().getSchedulerInstanceId()); } }
4. Configure Spring Boot Startup Class
Configure Quartz Scheduler in the Spring Boot startup class:
import ; import ; import ; import ; import ; import ; import ; @Component public class QuartzInitializer implements CommandLineRunner { @Autowired private SchedulerFactory schedulerFactory; @Override public void run(String... args) throws Exception { Scheduler scheduler = (); (); } @Bean public SchedulerFactory schedulerFactory() { return new StdSchedulerFactory(); } }
5. Define Job and Trigger
Using Spring@Configuration
Classes to define Job and Trigger:
import .*; import ; import ; @Configuration public class QuartzConfig { @Bean public JobDetail myJobDetail() { return () .withIdentity("myJob", "group1") .build(); } @Bean public Trigger myJobTrigger() { SimpleScheduleBuilder scheduleBuilder = () .withIntervalInSeconds(10) .repeatForever(); return () .forJob(myJobDetail()) .withIdentity("myJobTrigger", "group1") .withSchedule(scheduleBuilder) .build(); } }
6. Launch the application
After starting the Spring Boot application, Quartz will automatically create and schedule tasks based on the configuration. Because of the cluster mode configured, applications on multiple nodes share the same task scheduling information, ensuring that tasks are not executed repeatedly.
Things to note
-
Database table structure: Make sure that the table structure required by Quartz in the MySQL database. Can be set up
-schema=always
To generate these tables automatically. -
Cluster configuration: Ensure each node's
instanceId
is unique, can be setAUTO
Create automatically. - Time synchronization: Ensure time synchronization of all nodes in the cluster to avoid task scheduling problems caused by time inconsistency.
Through the above steps, you can successfully configure and use the Quartz cluster (MySQL data source) in your Spring Boot project.
The above is the detailed steps for configuring Quartz cluster under the Spring framework. For more information about configuring Quartz cluster in Spring, please pay attention to my other related articles!