SpringBoot整合quartz實現(xiàn)定時任務
Quartz基本概念
Quartz是一個任務調(diào)度框架,主要用于在特定時間觸發(fā)任務執(zhí)行。
Quartz的核心概念
- 調(diào)度器(Scheduler):負責任務的調(diào)度和管理,包括任務的啟動、暫停、恢復等操作。
- 任務(Job):需要實現(xiàn)org.quartz.Job接口的execute方法,定義了任務的具體執(zhí)行邏輯。
- 觸發(fā)器(Trigger):定義任務執(zhí)行的觸發(fā)條件,包括簡單觸發(fā)器(SimpleTrigger)和cron觸發(fā)器(CronTrigger)。
- 任務詳情(JobDetail):用于定義任務的詳細信息,如任務名、組名等。
- 任務構(gòu)建器(JobBuilder)和觸發(fā)器構(gòu)建器(TriggerBuilder):用于定義和構(gòu)建任務和觸發(fā)器的實例。
- 線程池(ThreadPool):用于并行調(diào)度執(zhí)行每個作業(yè),提高效率。
- 監(jiān)聽器(Listener):包括任務監(jiān)聽器、觸發(fā)器監(jiān)聽器和調(diào)度器監(jiān)聽器,用于監(jiān)聽任務和觸發(fā)器的狀態(tài)變化。
Quartz的基本使用步驟
- 創(chuàng)建任務類:實現(xiàn)Job接口的execute方法,定義任務的執(zhí)行邏輯。
- 生成任務詳情(JobDetail):通過JobBuilder定義任務的詳細信息。
- 生成觸發(fā)器(Trigger):通過TriggerBuilder定義任務的觸發(fā)條件,可以選擇使用簡單觸發(fā)器或cron觸發(fā)器。
- 獲取調(diào)度器(Scheduler):通過SchedulerFactory創(chuàng)建調(diào)度器對象,并將任務和觸發(fā)器綁定在一起,啟動調(diào)度器。
Quartz的優(yōu)點和缺點
- 優(yōu)點:支持復雜的調(diào)度需求,包括定時、重復執(zhí)行、并發(fā)執(zhí)行等;提供了豐富的API和工具類,易于使用和維護;支持Spring集成,方便在Spring項目中應用。
- 缺點:配置復雜,需要一定的學習成本;對于簡單的定時任務,使用Quartz可能會顯得過于復雜。
整合SpringBoot
第一步:添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>第二步:創(chuàng)建scheduler
package com.xy.quartz;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QuartzConfig {
@Bean
public Scheduler scheduler() throws SchedulerException {
SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
return schedulerFactoryBean.getScheduler();
}
}第三步:創(chuàng)建Job
import com.songwp.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
log.info("入?yún)?{}", jobDataMap.toString());
log.info("執(zhí)行定時任務的時間:{}", DateUtil.dateToStr(new Date()));
}
}第四步:創(chuàng)建任務信息類
import lombok.Data;
@Data
public class JobInfo {
private Long jobId;
private String cronExpression;
private String businessId;
}第五步:創(chuàng)建JobDetail和trigger創(chuàng)建包裝類
import com.songwp.domain.quartz.JobInfo;
import com.songwp.test.MyJob;
import org.quartz.*;
import java.util.Date;
public class QuartzBuilder {
public static final String RUN_CRON ="定時執(zhí)行";
public static final String RUN_ONE ="執(zhí)行一次";
private static final String JOB_NAME_PREFIX ="flow";
public static final String TRIGGER_NAME_PREFIX ="trigger.";
public static JobDetail createJobDetail(JobInfo jobInfo, String type){
String jobKey =JOB_NAME_PREFIX + jobInfo.getJobId();
if (RUN_ONE.equals(type)){
jobKey = JOB_NAME_PREFIX + new Date().getTime();
}
return JobBuilder.newJob(MyJob.class)
.withIdentity(jobKey,"my_group")
.usingJobData("businessId",jobInfo.getBusinessId())
.usingJobData("businessType","其他參數(shù)")
.storeDurably().build();
}
public static Trigger createTrigger(JobDetail jobDetail, JobInfo jobInfo){
return TriggerBuilder.newTrigger()
.forJob(jobDetail)
.withIdentity(TRIGGER_NAME_PREFIX + jobInfo.getJobId(),RUN_CRON)
.withSchedule(CronScheduleBuilder.cronSchedule(jobInfo.getCronExpression()))
.build();
}
}第六步:控制層接口實現(xiàn)接口
執(zhí)行一次、啟動定時、暫停任務
import com.songwp.config.quartz.QuartzBuilder;
import com.songwp.domain.quartz.JobInfo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
@RestController
@Slf4j
public class QuartzController {
@Autowired
private Scheduler scheduler;
/**
* 定時任務執(zhí)行(只執(zhí)行一次)
* @return
*/
@GetMapping("runOne")
public String runOne(){
JobInfo jobInfo = new JobInfo();
jobInfo.setJobId(1L);
jobInfo.setBusinessId("123");
jobInfo.setCronExpression("0/5 * * * * ?");
JobDetail jobDetail = QuartzBuilder.createJobDetail(jobInfo, QuartzBuilder.RUN_ONE);
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(jobDetail)
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
.build();
try {
scheduler.scheduleJob(jobDetail, trigger);
if (!scheduler.isStarted()) {
scheduler.start();
}
} catch (SchedulerException e) {
log.error(e.getMessage());
return "執(zhí)行失敗";
}
return "執(zhí)行成功";
}
/**
* 開始定時執(zhí)行
* @return 執(zhí)行結(jié)果
*/
@GetMapping("start")
public String start() {
try {
JobInfo jobInfo = new JobInfo();
jobInfo.setJobId(1L);
jobInfo.setBusinessId("123");
jobInfo.setCronExpression("0/5 * * * * ?");
TriggerKey triggerKey = new TriggerKey(QuartzBuilder.TRIGGER_NAME_PREFIX + jobInfo.getJobId(),QuartzBuilder.RUN_CRON);
if (scheduler.checkExists(triggerKey)) {
scheduler.resumeTrigger(triggerKey);
} else {
JobDetail jobDetail = QuartzBuilder.createJobDetail(jobInfo, QuartzBuilder.RUN_CRON);
Trigger trigger = QuartzBuilder.createTrigger(jobDetail, jobInfo);
scheduler.scheduleJob(jobDetail, trigger);
if (!scheduler.isStarted()) {
scheduler.start();
}
}
} catch (SchedulerException e) {
log.error(e.getMessage());
return "執(zhí)行失敗";
}
return "執(zhí)行成功";
}
/**
* 停止任務執(zhí)行
* @return 執(zhí)行結(jié)果
*/
@GetMapping("pause")
public String pause() {
try {
JobInfo jobInfo = new JobInfo();
jobInfo.setJobId(1L);
jobInfo.setBusinessId("123");
jobInfo.setCronExpression("0/5 * * * * ?");
TriggerKey triggerKey = new TriggerKey(QuartzBuilder.TRIGGER_NAME_PREFIX + jobInfo.getJobId(), QuartzBuilder.RUN_CRON);
if (scheduler.checkExists(triggerKey)) {
scheduler.pauseTrigger(triggerKey);
}
} catch (SchedulerException e) {
log.error(e.getMessage());
return "執(zhí)行失敗";
}
return "執(zhí)行成功";
}
/**
* 查詢已啟動狀態(tài)的任務,然后重新執(zhí)行
*/
@PostConstruct
public void init(){
log.info("查詢已啟動狀態(tài)的任務,然后重新執(zhí)行");
start();
}
}最后訪問接口:
http://localhost:8080/runOne
http://localhost:8080/start
http://localhost:8080/pause

正常情況下的步驟應該是這樣:
1、創(chuàng)建任務時記錄到任務表job_info,此時初始狀態(tài)為0
2、啟動任務時更新任務表狀態(tài),更新為1
3、如果應用關閉了,那么在下次應用啟動的時候,需要把狀態(tài)為1的任務也給啟動了,就不需要認為再去調(diào)接口啟動。
以上就是SpringBoot整合quartz實現(xiàn)定時任務的詳細內(nèi)容,更多關于SpringBoot quartz定時任務的資料請關注腳本之家其它相關文章!
相關文章
spring?cloud?gateway中配置uri三種方式
gateway?組件是SpringCloud?組件中的網(wǎng)關組件,主要是解決路由轉(zhuǎn)發(fā)的問題,跟nginx有點類似,區(qū)別是nginx多用在前端上,gateway用在后端上,本文給大家介紹的非常詳細,需要的朋友參考下吧2023-08-08
springboot實現(xiàn)指定mybatis中mapper文件掃描路徑
這篇文章主要介紹了springboot實現(xiàn)指定mybatis中mapper文件掃描路徑方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
詳解PipedInputStream和PipedOutputStream_動力節(jié)點Java學院整理
這篇文章主要為大家詳細介紹了管道PipedInputStream和PipedOutputStream,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
SpringMVC使用ResponseEntity實現(xiàn)文件上傳下載
這篇文章主要為大家介紹了SpringMVC使用ResponseEntity實現(xiàn)文件上傳下載,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
SpringBoot集成Validation參數(shù)校驗
這篇文章主要為大家詳細介紹了SpringBoot集成Validation參數(shù)校驗,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01

