Based on the environment
SpringBoot 2.0 provides automatic configuration of Quartz scheduled tasks. It relies on the Spring-boot-starter-Quartz component and does not need to be integrated
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
Copy the code
Environment Version:
- SpringBoot 2.1.6. RELEASE
- Java 8
Scheduled Task Configuration
Add the dependent
Add Quartz, Jpa, mysql driver, lombok dependencies to POM.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
Copy the code
Adding a Configuration File
Adding a Database Configuration
spring:
datasource:
primary:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: hmdt
url: jdbc:mysql://db/bussines_db? useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
quartz:
url: jdbc:mysql://db/bussines_quartz? useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: hmdt
quartz:
# Configure related attributes
properties:
org:
quartz:
scheduler:
instanceName: clusteredScheduler
instanceId: AUTO
jobStore:
# data source name
dataSource: quartzDataSource
class: org.quartz.impl.jdbcjobstore.JobStoreTX
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
tablePrefix: QRTZ_
isClustered: true
clusterCheckinInterval: 1000
useProperties: false
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 10
threadPriority: 5
threadsInheritContextClassLoaderOfInitializingThread: true
job-store-type: jdbc
Initialize the table structure
jdbc:
initialize-schema: never
jpa:
hibernate:
ddl-auto: update
show-sql: true
database-platform: org.hibernate.dialect.MySQL55Dialect
properties:
hibernate:
format_sql: true
use_sql_comments: true
Copy the code
There is also a sample database configuration in Spring.Quartz. Properties, but the test configuration is not valid, and since you need to specify connection pool information, this configuration is easier to manage in the Spring connection pool
Download the official website to build sentences
Although JPA is used, Spring does not automatically build tables for us because there is no entity association. You need to download SQL scripts from the official website
Quartz website
Motion-2.3.0-snapshot \ SRC \org\quartz\impl\ jdbcJobStore supports a large number of database table building phrases, select the corresponding use
Configuring multiple Data Sources
Multiple configuration sources have been detailed in this article about configuration samples and the reasons for them
Springboot2.x Data JPA multi-data source crawl pit
Write the database configuration and use the HikariCP connection pool uniformly
package com.gcb.invest.config;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.quartz.QuartzDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/** * Data source configuration for scheduled tasks **@authorJia Yang * F@dateThe 2019-07-28 21:52 * /
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties("spring.datasource.primary")
public DataSourceProperties primaryDataSourceProperties(a) {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("spring.datasource.primary.configuration")
public HikariDataSource firstDataSource(a) {
return primaryDataSourceProperties().initializeDataSourceBuilder()
.type(HikariDataSource.class).build();
}
@Bean
@ConfigurationProperties("spring.datasource.quartz")
public DataSourceProperties quartzDataSourceProperties(a) {
return new DataSourceProperties();
}
@Bean
@QuartzDataSource
@ConfigurationProperties("spring.datasource.quartz.configuration")
public HikariDataSource quartzDataSource(a) {
returnquartzDataSourceProperties().initializeDataSourceBuilder() .type(HikariDataSource.class).build(); }}Copy the code
Scheduled Task Configuration
Configure Example 1 — Bean injection
Writing scheduled tasks is easier to use thanks to Spring’s encapsulation
Here through the inner class configuration timing task, and using the @ DisallowConcurrentExecution annotations to specify its shall not concurrently in a distributed environment
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.QuartzJobBean;
/** * Scheduled task configuration **@author: F Jiayang *@date: 2019/7/29 for * /
@Slf4j
@Configuration
public class QuartzConfig {
/** * Test scheduled task build **@return* /
@Bean
public JobDetail testTaskJobDetail(a) {
return JobBuilder.newJob(TestTask.class)
.withIdentity(TestTask.class.getName())
.storeDurably(true)
.build();
}
/** * Test scheduled task configuration **@return* /
@Bean
public Trigger testTaskTrigger(a) {
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/2 * * * *?");
return TriggerBuilder.newTrigger()
.forJob(testTaskJobDetail())
.withIdentity(TestTask.class.getName())
.withSchedule(scheduleBuilder)
.build();
}
@DisallowConcurrentExecution
private class TestTask extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.debug("Perform scheduled test task"); }}}Copy the code
Configuration Example 2 – Scheduler injection
Alternatively, you can build the task manually using the injection scheduler, but the scheduler will not be created until this method is called
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.UUID;
/ * * *@author: F Jiayang *@date: 2019/7/29 8:59 * /
@Service
@Transactional(rollbackFor = Exception.class)
public class QuartzTimerService {
@Autowired
private Scheduler scheduler;
public void buildGoodStockTimer(a) throws Exception {
// Task name
String name = UUID.randomUUID().toString();
// Task group
String group = CustomQuartzJob.class.getName();
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/1 * * * *?");
// Create a task
JobDetail jobDetail = JobBuilder.newJob(CustomQuartzJob.class).withIdentity(name,group).build();
// Create task trigger
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name,group).withSchedule(scheduleBuilder).build();
// Bind the trigger and task to the schedulerscheduler.scheduleJob(jobDetail, trigger); }}Copy the code
Scheduled Task class
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
/ * * *@author: F Jiayang *@date: 2019/7/29 her * /
@Slf4j
@DisallowConcurrentExecution
public class CustomQuartzJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.info("Perform scheduled tasks"); }}Copy the code
The execution result
Execute successfully
Automatically migrates job nodes in a distributed environment