SprinBoot整合Quart實現定時排程的示例程式碼
阿新 • • 發佈:2020-10-26
Quartz是一款開源的定時任務排程框架,Quartz的官網是:http://www.quartz-scheduler.org/。本文主要是講訴使用springboot整合quartz實現定時任務排程管理的用例。主要的內容有如下三部分:
1. springboot整合quartz的相關配置
2. 實現基於simpleTrigger的定時任務
3. 實現基於cronTrigger的定時任務
一、匯入相關的pom依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bruce.quartz.springboot.demo</groupId> <artifactId>Quartz-SpringBoot-0426</artifactId> <version>1.0-SNAPSHOT</version> <!--匯入SpringBoot--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--Quartz任務排程的包 --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
二、建立SpringBoot的啟動類
package com.anhong; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.impl.StdSchedulerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; /** * @BelongsProject: Quartz-SpringBoot-0426 * @BelongsPackage: com.anhong * @Author: anhong * @CreateTime: 2020-10-24 09:24 * @Description: TODO */ @SpringBootApplication public class APP { public static void main(String[] args) { SpringApplication.run(APP.class,args); } /** * 向Spring容器中初始注入scheduler */ @Bean public Scheduler scheduler() throws SchedulerException { SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory(); return schedulerFactoryBean.getScheduler(); } }
三、建立quartz的作業類
package com.anhong.job; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import java.text.SimpleDateFormat; import java.util.Date; /** * @BelongsProject: Quartz-SpringBoot-0426 * @BelongsPackage: com.anhong.job * @Author: anhong * @CreateTime: 2020-10-24 09:35 * @Description: 任務類,實現JOB介面,重寫其中的方法 */ public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String time=simpleDateFormat.format(new Date()); System.out.println("各位老鐵,早上好!節日快樂啊!"+time); } }
四、建立quartz的配置類
package com.anhong.config; import com.anhong.bean.TaskInfo; import com.bruce.job.MyJob; import org.quartz.*; import org.quartz.impl.matchers.GroupMatcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; /** * @BelongsProject: Quartz-SpringBoot-0426 * @BelongsPackage: com.anhong.config * @Author: anhong * @CreateTime: 2020-10-24 10:10 * @Description: Quartz配置類 */ @SpringBootConfiguration public class QuartzConfig { //任務排程器 @Autowired private Scheduler scheduler; /** * 01-開啟任務 */ public void startJob(){ try { openJob(scheduler); //啟動任務 scheduler.start(); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 02-暫停某個任務 */ public void pauseJob(String name,String group) throws Exception{ //任務的標識類 JobKey jobKey=new JobKey(name,group); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if(jobDetail!=null){ //暫停某個任務 scheduler.pauseJob(jobKey); }else{ System.out.println("該任務不存在!"); } } /** * 03-查詢所有的任務基本資訊 * @return */ public List<TaskInfo> getAllJobsInfo() throws Exception{ List<TaskInfo> list=new ArrayList<TaskInfo>(); //所有任務組 List<String> jobGroupNames = scheduler.getJobGroupNames(); for (String jobGroupName : jobGroupNames) { Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.<JobKey>groupEquals(jobGroupName)); for (JobKey jobKey : jobKeys) { List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey); for (Trigger trigger : triggers) { Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); JobDetail jobDetail = scheduler.getJobDetail(jobKey); String cronExpression=""; //cron表示式 String cronDescription=""; //描述資訊 if(trigger instanceof CronTrigger){ CronTrigger cronTrigger=(CronTrigger)trigger; //cron表示式 cronExpression = cronTrigger.getCronExpression(); cronDescription=cronTrigger.getDescription(); } TaskInfo taskInfo=new TaskInfo(); taskInfo.setJobName(jobKey.getName()); taskInfo.setJobGroup(jobKey.getGroup()); taskInfo.setJobDescrption(jobDetail.getDescription()); taskInfo.setStatus(triggerState.name()); //任務的狀態 taskInfo.setCronExpression(cronExpression); taskInfo.setCronDescription(cronDescription); list.add(taskInfo); } } } return list; } /** * 開啟一個任務 * @param scheduler */ private void openJob(Scheduler scheduler){ try { //1.建立一個JobDetail JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("job1","group1").build(); //2.觸發器表示式物件 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/4 * * * * ?"); //CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("30 25 16 * * ?"); //3.準備一個觸發器物件 CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1","triggergroup1") .withSchedule(cronScheduleBuilder).build(); //4.開始排程 scheduler.scheduleJob(jobDetail,cronTrigger); } catch (SchedulerException e) { e.printStackTrace(); } finally { } } /** * 04-恢復某個任務的執行 * @param name * @param group */ public void resumeJob(String name,String group) throws Exception{ JobKey jobKey=new JobKey(name,group); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if(jobDetail!=null){ scheduler.resumeJob(jobKey); }else{ System.out.println("要恢復的任務不存在!"); } } /** * 05-刪除某一個任務 * @param name * @param group * @throws Exception */ public void deleteJob(String name,group); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if(jobDetail!=null){ scheduler.deleteJob(jobKey); }else{ System.out.println("要刪除的任務不存在!"); } } /** * 06-動態的修改任務執行的表示式,觸發規則 * @param name * @param group * @return */ public boolean modifyJob(String name,String group,String newTime) throws Exception{ Date date=null; TriggerKey triggerKey=new TriggerKey(name,group); Trigger trigger = scheduler.getTrigger(triggerKey); CronTrigger cronTrigger=null; if(trigger instanceof CronTrigger){ cronTrigger=(CronTrigger)trigger; //表示式 String cronExpression = cronTrigger.getCronExpression(); if(!cronExpression.equalsIgnoreCase(newTime)){ System.out.println("需要修改原來的表示式:"+cronExpression+"為:"+newTime); CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(newTime); //新的觸發器 CronTrigger cronTrigger1 = TriggerBuilder.newTrigger().withIdentity(name,group).withSchedule(cronScheduleBuilder).build(); date = scheduler.rescheduleJob(triggerKey,cronTrigger1); }else{ System.out.println("不用修改!和原來的一樣!"); } } if(date!=null){ return true; }else{ return false; } } }
任務物件
package com.anhong.bean; /** * @BelongsProject: Quartz-SpringBoot-0426 * @BelongsPackage: com.anhong.bean * @Author: anhong * @CreateTime: 2020-10-24 10:24 * @Description: 任務物件 */ public class TaskInfo { private String jobName; private String jobGroup; private String jobDescrption; private String status; private String cronExpression; private String cronDescription; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobGroup() { return jobGroup; } public void setJobGroup(String jobGroup) { this.jobGroup = jobGroup; } public String getJobDescrption() { return jobDescrption; } public void setJobDescrption(String jobDescrption) { this.jobDescrption = jobDescrption; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getCronDescription() { return cronDescription; } public void setCronDescription(String cronDescription) { this.cronDescription = cronDescription; } }
五、建立Quartz的監聽類
package com.anhong; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.impl.StdSchedulerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextRefreshedEvent; @Configuration public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent> { @Autowired private QuartzScheduler quartzScheduler; /** * 初始啟動quartz */ @Override public void onApplicationEvent(ContextRefreshedEvent event) { try { quartzScheduler.startJob(); System.out.println("任務已經啟動..."); } catch (SchedulerException e) { e.printStackTrace(); } } /** * 初始注入scheduler * @return * @throws SchedulerException */ @Bean public Scheduler scheduler() throws SchedulerException{ SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory(); return schedulerFactoryBean.getScheduler(); } }
六、建立控制器
package com.anhong.controller; import com.anhong.bean.TaskInfo; import com.anhong.config.QuartzConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @BelongsProject: Quartz-SpringBoot-0426 * @BelongsPackage: com.anhong.controller * @Author: anhong * @CreateTime: 2020-10-24 10:43 * @Description: TODO */ @RestController @RequestMapping("/quartz") public class QuartzController { @Autowired QuartzConfig quartzConfig; /** * 01-開啟一個定時任務 * * @return */ @RequestMapping("/start") public String startQuartzJob() { try { quartzConfig.startJob(); } catch (Exception e) { e.printStackTrace(); return "定時任務開啟異常~~~"; } return "定時任務開啟成功~~~"; } /** * 02-暫停任務 * * @param name * @param group * @return */ @RequestMapping("/pauseJob") public String pauseJob(String name,String group) { try { quartzConfig.pauseJob(name,group); } catch (Exception e) { e.printStackTrace(); return name + "任務暫停異常"; } finally { } return name + "任務被暫停"; } /** * 03-查詢所有的任務基本資訊 * * @return */ @RequestMapping("/infos") public List<TaskInfo> getAllJobsInfo() { try { return quartzConfig.getAllJobsInfo(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 04-恢復某個任務的執行 * * @param name * @param group */ @RequestMapping("/resumeJob") public String resumeJob(String name,String group) { try { quartzConfig.resumeJob(name,group); } catch (Exception e) { e.printStackTrace(); return name + "任務被恢復異常!"; } finally { } return name + "任務被恢復啦!"; } /** * 05-刪除某一個任務 * * @param name * @param group * @throws Exception */ @RequestMapping("/deleteJob") public String deleteJob(String name,String group) { try { quartzConfig.deleteJob(name,group); } catch (Exception e) { e.printStackTrace(); return name + "任務刪除異常!"; } finally { } return name + "任務被刪除啦!"; } /** * 06-動態的修改任務執行的表示式,觸發規則 * * @param name * @param group * @return */ @RequestMapping("/modifyJob") public String modifyJob(String name,String newTime) { boolean flag = false; try { flag = quartzConfig.modifyJob(name,group,newTime); } catch (Exception e) { e.printStackTrace(); } finally { } if (flag) { return name + "任務時間表達式修改為:" + newTime; } else { return name + "任務時間表達式失敗!"; } } }
總結:SpringBoot整合Quertz實現定時排程的大致步驟實現就如上,在很多微服務商城專案上都會用到定時排程,在根據實際的專案業務需要,我們只需要把以上的一些配置做適當的修改來滿足自己業務的需要。
到此這篇關於SprinBoot整合Quart實現定時排程的示例程式碼的文章就介紹到這了,更多相關SprinBoot整合Quart內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!