導入依賴
<!--添加quartz的依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
application.yml配置文件
spring:
quartz:
#相關屬性配置
properties:
org:
quartz:
scheduler:
instanceName: clusteredScheduler
instanceId: AUTO
jobStore:
class: org.quartz.impl.jdbcjobstore.JobStoreTX
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
tablePrefix: QRTZ_
isClustered: true
clusterCheckinInterval: 10000
useProperties: false
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 10
threadPriority: 5
threadsInheritContextClassLoaderOfInitializingThread: true
#數據庫方式
job-store-type: jdbc
#初始化表結構.初次使用的時候會在庫中生成表格,后期注釋掉即可.或者初始使用值為always,然后將值改為never
#jdbc:
#initialize-schema: always
quartz配置類
package com.theeternity.common.quartz;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @program: ApiBoot
* @description: quartz配置類
* @author: TheEternity Zhang
* @create: 2019-03-11 11:01
*/
@Configuration
public class QuartzConfig {
@Bean
public JobDetail uploadTaskDetail() {
return JobBuilder.newJob(TestQuartz.class).withIdentity("testQuartz").storeDurably().build();
}
@Bean
public Trigger uploadTaskTrigger() {
//設置執行頻率
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("*/5 * * * * ?");
return TriggerBuilder.newTrigger().forJob(uploadTaskDetail())
.withIdentity("testQuartz")
.withSchedule(scheduleBuilder)
.build();
}
}
quartz具體執行類
package com.theeternity.common.quartz;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.util.UUID;
/**
* @program: ApiBoot
* @description: 測試quartz
* @author: TheEternity Zhang
* @create: 2019-03-11 11:01
* @DisallowConcurrentExecution 注解得作用是:是否並發執行,系統默認為true,即第一個任務還未執行完整,第二個任務如果到了執行時間,則會立馬開啟新線程執行任務,這樣如果我們是從數據庫讀取信息,兩次重復讀取可能出現重復執行任務的情況,所以我們需要將這個值設置為false,這樣第二個任務會往后推遲,只有在第一個任務執行完成后才會執行第二個任務。
*/
@DisallowConcurrentExecution
public class TestQuartz extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String random= UUID.randomUUID().toString();
System.out.println("任務開始:"+random);
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任務結束:"+random);
}
}
參考文檔:
https://www.jianshu.com/p/056281e057b3 (流程參考)
https://docs.spring.io/spring-boot/docs/2.0.x-SNAPSHOT/reference/htmlsingle/#boot-features-quartz (官方文檔)
https://blog.csdn.net/tushuping/article/details/79636207 (具體代碼)