點擊上方「Java基基」,選擇「設為星標」
做積極的人,而不是積極廢人!
來源:gyoomi.blog.csdn.net/article/details/83382000
定時任務調度是Java開發中不可或缺的重要部分,但是Java自帶的Time等任務調度類在實際項目中不好用。所以Quartz和Spring Task就成了我們項目開發技術選型最多的,在這裡我們著重探討一下Quartz在Spring Boot 2.X版本中的使用。
Quartz是OpenSymphony開源組織在Job scheduling領域的開源項目,它可以與J2EE與J2SE應用程式相結合也可以單獨使用。Quartz可以用來創建簡單或為運行十個,百個,甚至是好幾萬個Jobs這樣複雜的日程序表。Jobs可以做成標準的Java組件或 EJBs。
Quartz是一個任務日程管理系統,一個在預先確定(被納入日程)的時間到達時,負責執行(或者通知)其他軟體組件的系統。
Quartz用一個小Java庫發布文件(.jar文件),這個庫文件包含了所有Quartz核心功能。這些功能的主要接口(API)是Scheduler接口。它提供了簡單的操作,例如:將任務納入日程或者從日程中取消,開始/停止/暫停日程進度。
官方網站:
http://quartz-scheduler.org/
圖片多個定時的圖示如下:
圖片對比下配置xml中的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!--
Spring整合Quartz進行配置遵循下面的步驟:
1:定義工作任務的Job
2:定義觸發器Trigger,並將觸發器與工作任務綁定
3:定義調度器,並將Trigger註冊到Scheduler
-->
<!-- 1:定義任務的bean ,這裡使用JobDetailFactoryBean,也可以使用MethodInvokingJobDetailFactoryBean ,配置類似-->
<bean name="hwJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<!-- 指定job的名稱 -->
<property name="name" value="hw_job"/>
<!-- 指定job的分組 -->
<property name="group" value="hw_group"/>
<!-- 指定具體的job類 -->
<property name="jobClass" value="com.dufy.spring.quartz.chapter01.job.HelloWorldJob"/>
<!-- 必須設置為true,如果為false,當沒有活動的觸發器與之關聯時會在調度器中會刪除該任務 -->
<property name="durability" value="true"/>
<!-- 指定spring容器的key,如果不設定在job中的jobmap中是獲取不到spring容器的 -->
<property name="applicationContextJobDataKey" value="applicationContext"/>
</bean>
<!-- 2.1:定義觸發器的bean,定義一個Simple的Trigger,一個觸發器只能和一個任務進行綁定 -->
<!-- <bean name="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
指定Trigger的名稱
<property name="name" value="hw_trigger"/>
指定Trigger的名稱
<property name="group" value="hw_trigger_group"/>
指定Tirgger綁定的Job
<property name="jobDetail" ref="hwJob"/>
指定Trigger的延遲時間 1s後運行
<property name="startDelay" value="1000"/>
指定Trigger的重複間隔 5s
<property name="repeatInterval" value="5000"/>
指定Trigger的重複次數
<property name="repeatCount" value="5"/>
</bean> -->
<!-- 2.2:定義觸發器的bean,定義一個Cron的Trigger,一個觸發器只能和一個任務進行綁定 -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<!-- 指定Trigger的名稱 -->
<property name="name" value="hw_trigger"/>
<!-- 指定Trigger的名稱 -->
<property name="group" value="hw_trigger_group"/>
<!-- 指定Tirgger綁定的Job -->
<property name="jobDetail" ref="hwJob"/>
<!-- 指定Cron 的表達式 ,當前是每隔1s運行一次 -->
<property name="cronExpression" value="0/1 * * * * ?" />
</bean>
<!-- 3.定義調度器,並將Trigger註冊到調度器中 -->
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<!-- <ref bean="simpleTrigger"/> -->
<ref bean="cronTrigger"/>
</list>
</property>
<!-- <property name="autoStartup" value="true" /> -->
</bean>
</beans>項目是基於Spring Boot2.x版本的。
圖片<!-- quartz依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
圖片application-quartz.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
#初始化表結構
#jdbc:
#initialize-schema: never簡單任務
圖片代碼如下:
public class MyJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("start My Job:" + LocalDateTime.now());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end My Job:" + LocalDateTime.now());
}
}CRON任務
圖片public class MyCronJob extends QuartzJobBean {
@Autowired
IndexController indexController;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("任務執行了" + new Date());
// indexController.testMail();
}
}@Configuration
public class QuartzConfiguration {
// 使用jobDetail包裝job
@Bean
public JobDetail myJobDetail() {
return JobBuilder.newJob(MyJob.class).withIdentity("myJob").storeDurably().build();
}
// 把jobDetail註冊到trigger上去
@Bean
public Trigger myJobTrigger() {
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(15).repeatForever();
return TriggerBuilder.newTrigger()
.forJob(myJobDetail())
.withIdentity("myJobTrigger")
.withSchedule(scheduleBuilder)
.build();
}
// 使用jobDetail包裝job
@Bean
public JobDetail myCronJobDetail() {
return JobBuilder.newJob(MyCronJob.class).withIdentity("myCronJob").storeDurably().build();
}
// 把jobDetail註冊到Cron表達式的trigger上去
@Bean
public Trigger CronJobTrigger() {
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
return TriggerBuilder.newTrigger()
.forJob(myCronJobDetail())
.withIdentity("myCronJobTrigger")
.withSchedule(cronScheduleBuilder)
.build();
}
}其實上面的配置就等價於在傳統的xml中配置bean是一樣的。
圖片至此,SpringBoot集成Quartz的完畢。
Spring Boot集成quartz還是比較簡單的。
其實還有更高級的用法,就是前臺動態創建和控制定時任務,後面有時間再完善。大家先把這種最簡單的基本用法熟練掌握。
圖片圖片首先點擊右下方在看,再長按下方二維碼關注哦,並後臺回復二維碼
歡迎加入我的知識星球,一起探討架構,交流源碼。加入方式,長按下方二維碼噢:
已在知識星球更新源碼解析如下:
最近更新《芋道 SpringBoot 2.X 入門》系列,已經 20 餘篇,覆蓋了 MyBatis、Redis、MongoDB、ES、分庫分表、讀寫分離、SpringMVC、Webflux、權限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能測試等等內容。
提供近 3W 行代碼的 SpringBoot 示例,以及超 4W 行代碼的電商微服務項目。
獲取方式:點「在看」,關注公眾號並回復 666 領取,更多內容陸續奉上。
文章有幫助的話,在看,轉發吧。
謝謝支持喲 (*^__^*)