温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用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