中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用SprinBoot整合Quart實現定時調度的方法

發布時間:2020-10-28 02:29:18 來源:億速云 閱讀:155 作者:Leah 欄目:開發技術

本篇文章為大家展示了使用SprinBoot整合Quart實現定時調度的方法,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

1. springboot整合quartz的相關配置

2. 實現基于simpleTrigger的定時任務

3. 實現基于cronTrigger的定時任務

一、導入相關的pom依賴

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<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<&#63; 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 * * * * &#63;");
  //CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("30 25 16 * * &#63;");
  //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,String group) throws Exception{
 JobKey jobKey=new JobKey(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 group, 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實現定時調度的方法,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

呼伦贝尔市| 错那县| 清丰县| 太和县| 广饶县| 洪湖市| 达州市| 长岛县| 定襄县| 中江县| 资源县| 个旧市| 安丘市| 都匀市| 鹤壁市| 西乌| 徐汇区| 信阳市| 灯塔市| 萨迦县| 蓝田县| 秭归县| 雅江县| 宁河县| 晋中市| 临猗县| 泾川县| 同心县| 渭源县| 吕梁市| 佛学| 江达县| 舞阳县| 红桥区| 华蓥市| 朝阳市| 黄陵县| 遂平县| 德安县| 禄劝| 天等县|