Spring Boot Sample 031之spring-boot-schedule-quartz
一、环境
Idea 2020.1
JDK 1.8
maven
二、目的
spring boot 通过整合quartz
gitHub地址: https://github.com/ouyushan/ouyushan-spring-boot-samples
三、步骤
3.1、点击File -> New Project -> Spring Initializer,点击next
3.2、在对应地方修改自己的项目信息
3.3、选择Web依赖,选中Spring Web、Spring Boot DevTools、Quartz Scheduler。可以选择Spring Boot版本,本次默认为2.3.0,点击Next
3.4、项目结构
四、添加文件
pom.xml文件
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
quartz.properties文件, 默认使用hikaricp数据源
固定前缀org.quartz
主要分为scheduler、threadPool、jobStore、plugin等部分
org.quartz.scheduler.instanceName=DefaultQuartzScheduler
org.quartz.scheduler.rmi.export=false
org.quartz.scheduler.rmi.proxy=false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
实例化ThreadPool时,使用的线程类为SimpleThreadPool
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
threadCount和threadPriority将以setter的形式注入ThreadPool实例
并发个数
org.quartz.threadPool.threadCount=5
优先级
org.quartz.threadPool.threadPriority=5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true
org.quartz.jobStore.misfireThreshold=5000
默认存储在内存中
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore
持久化
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties=true
org.quartz.jobStore.tablePrefix=QRTZ_
org.quartz.jobStore.dataSource=qzDS
org.quartz.dataSource.qzDS.driver=com.mysql.cj.jdbc.Driver
org.quartz.dataSource.qzDS.provider=hikaricp
使用hikaricp 时URL 大写
org.quartz.dataSource.qzDS.URL=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
org.quartz.dataSource.qzDS.user=root
org.quartz.dataSource.qzDS.password=root
org.quartz.dataSource.qzDS.maxConnections=10
SchedulerConfig.java
注意 定义executorListener后,quartz的配置文件名称不能为默认的quartz.properties ,否则会初始化两次导致失败
package org.ouyushan.springboot.scheduler.quartz.config;
import org.quartz.Scheduler;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.io.IOException;
import java.util.Properties;
/**
-
@Description:
-
@Author: ouyushan
-
@Email: ouyushan@hotmail.com
-
@Date: 2020/6/11 15:58
*/
@Configuration
@EnableScheduling
public class SchedulerConfig {@Bean
public SchedulerFactoryBean schedulerFactory() throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setQuartzProperties(quartzProperties());
return factory;
}@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
//在quartz.properties中的属性被读取并注入后再初始化对象
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}/**
- quartz初始化监听器
- 定义该bean,quartz.properties必须改名
/
/ @Bean
public QuartzInitializerListener executorListener() {
return new QuartzInitializerListener();
}*/
/**
- 通过SchedulerFactoryBean获取Scheduler的实例
*/
@Bean
public Scheduler scheduler() throws IOException {
return schedulerFactory().getScheduler();
}
}
HelloJob.java
package org.ouyushan.springboot.scheduler.quartz.job;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.time.LocalDateTime;
/**
-
@Description:
-
@Author: ouyushan
-
@Email: ouyushan@hotmail.com
-
@Date: 2020/6/11 16:07
*/
public class HelloJob implements Job {private String name;
public void setName(String name) {
this.name = name;
}@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Hello:" + name + LocalDateTime.now());
}
}
HiJob.java
package org.ouyushan.springboot.scheduler.quartz.job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.time.LocalDateTime;
/**
-
@Description:
-
@Author: ouyushan
-
@Email: ouyushan@hotmail.com
-
@Date: 2020/6/11 16:25
*/
public class HiJob extends QuartzJobBean {private String name;
public void setName(String name) {
this.name = name;
}@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println("Hi:" + name + LocalDateTime.now());
}
}
SpringBootSchedulerQuartzApplication.java
package org.ouyushan.springboot.scheduler.quartz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class SpringBootSchedulerQuartzApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSchedulerQuartzApplication.class, args);
}
}
五、测试
SpringBootSchedulerQuartzApplicationTests.java
package org.ouyushan.springboot.scheduler.quartz;
import org.junit.jupiter.api.Test;
import org.ouyushan.springboot.scheduler.quartz.job.HelloJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
@SpringBootTest
@AutoConfigureWebMvc
class SpringBootSchedulerQuartzApplicationTests {
@Test
public void test() throws SchedulerException {
// 1. 创建工厂类 SchedulerFactory
SchedulerFactory factory = new StdSchedulerFactory();
// 2. 通过 getScheduler() 方法获得 Scheduler 实例
Scheduler scheduler = factory.getScheduler();
// 3. 使用上文定义的 HelloJob
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
//job 的name和group
.withIdentity("jobName", "jobGroup")
.usingJobData("name","ouyushan")
.build();
//3秒后启动任务
Date statTime = new Date(System.currentTimeMillis() + 3000);
// 4. 启动 Scheduler
scheduler.start();
// 5. 创建Trigger
//使用SimpleScheduleBuilder或者CronScheduleBuilder
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("jobTriggerName", "jobTriggerGroup")
.withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次
.build();
// 6. 注册任务和定时器
scheduler.scheduleJob(jobDetail, trigger);
}
}
执行测试用例后
SELECT * FROM mybatis.qrtz_job_details;
表中已记录任务详情数据
解除外键
SET foreign_key_checks = 0
激活外键
SET foreign_key_checks = 1