欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈SpringBoot集成Quartz动态定时任务

程序员文章站 2023-12-09 17:54:33
springboot自带schedule 沿用的springboot少xml配置的优良传统,本身支持表达式等多种定时任务 注意在程序启动的时候加上@enablesch...

springboot自带schedule

沿用的springboot少xml配置的优良传统,本身支持表达式等多种定时任务
注意在程序启动的时候加上@enablescheduling

@scheduled(cron="0/5 * * * * ?")
 public void job(){
  system.out.println("每五秒执行一次");
 }

为什么要使用quartz

多任务情况下,quartz更容易管理,可以实现动态配置
执行时间表达式:

浅谈SpringBoot集成Quartz动态定时任务

表达式示例:

浅谈SpringBoot集成Quartz动态定时任务

集成quartz

如何搭建springboot就不再细说,官网和网上的教程很多。

maven依赖

<dependency>
   <groupid>org.quartz-scheduler</groupid>
   <artifactid>quartz</artifactid>
   <version>2.2.1</version>
  </dependency>

 测试job类
schedulerquartzjob1和schedulerquartzjob2代码差不多就不一一列出

package com.yvan.quartz.job;

import org.quartz.job;
import org.quartz.jobexecutioncontext;
import org.quartz.jobexecutionexception;
/**
 * 实现job接口
 * @author yvan
 *
 */
public class schedulerquartzjob1 implements job{
 private void before(){
  system.out.println("任务开始执行");
 }

 @override
 public void execute(jobexecutioncontext arg0) throws jobexecutionexception {
  before();
  system.out.println("开始:"+system.currenttimemillis());
  // todo 业务
  system.out.println("结束:"+system.currenttimemillis());
  after();
 }

 private void after(){
  system.out.println("任务开始执行");
 }

}

任务调用处理
将其拆分成两个部分

实例化job,将任务触发器加入任务调度中

 private void startjob1(scheduler scheduler) throws schedulerexception {
  // 通过jobbuilder构建jobdetail实例,jobdetail规定只能是实现job接口的实例
  // jobdetail 是具体job实例
  jobdetail jobdetail = jobbuilder.newjob(schedulerquartzjob1.class).withidentity("job1", "group1").build();
  // 基于表达式构建触发器
  cronschedulebuilder cronschedulebuilder = cronschedulebuilder.cronschedule("0/5 * * * * ?");
  // crontrigger表达式触发器 继承于trigger
  // triggerbuilder 用于构建触发器实例
  crontrigger crontrigger = triggerbuilder.newtrigger().withidentity("job1", "group1")
    .withschedule(cronschedulebuilder).build();
  scheduler.schedulejob(jobdetail, crontrigger);
 }

 private void startjob2(scheduler scheduler) throws schedulerexception {
  jobdetail jobdetail = jobbuilder.newjob(schedulerquartzjob2.class).withidentity("job2", "group2").build();
  cronschedulebuilder cronschedulebuilder = cronschedulebuilder.cronschedule("0 0/5 * * * ?");
  crontrigger crontrigger = triggerbuilder.newtrigger().withidentity("job2", "group2")
    .withschedule(cronschedulebuilder).build();
  scheduler.schedulejob(jobdetail, crontrigger);
 }

对外提供关于动态管理任务的方法

 /**
  * 开始执行所有任务
  * 
  * @throws schedulerexception
  */
 public void startjob() throws schedulerexception {
  startjob1(scheduler);
  startjob2(scheduler);
  scheduler.start();
 }

 /**
  * 获取job信息
  * 
  * @param name
  * @param group
  * @return
  * @throws schedulerexception
  */
 public string getjobinfo(string name, string group) throws schedulerexception {
  triggerkey triggerkey = new triggerkey(name, group);
  crontrigger crontrigger = (crontrigger) scheduler.gettrigger(triggerkey);
  return string.format("time:%s,state:%s", crontrigger.getcronexpression(),
    scheduler.gettriggerstate(triggerkey).name());
 }

 /**
  * 修改某个任务的执行时间
  * 
  * @param name
  * @param group
  * @param time
  * @return
  * @throws schedulerexception
  */
 public boolean modifyjob(string name, string group, string time) throws schedulerexception {
  date date = null;
  triggerkey triggerkey = new triggerkey(name, group);
  crontrigger crontrigger = (crontrigger) scheduler.gettrigger(triggerkey);
  string oldtime = crontrigger.getcronexpression();
  if (!oldtime.equalsignorecase(time)) {
   cronschedulebuilder cronschedulebuilder = cronschedulebuilder.cronschedule(time);
   crontrigger trigger = triggerbuilder.newtrigger().withidentity(name, group)
     .withschedule(cronschedulebuilder).build();
   date = scheduler.reschedulejob(triggerkey, trigger);
  }
  return date != null;
 }

 /**
  * 暂停所有任务
  * 
  * @throws schedulerexception
  */
 public void pausealljob() throws schedulerexception {
  scheduler.pauseall();
 }

 /**
  * 暂停某个任务
  * 
  * @param name
  * @param group
  * @throws schedulerexception
  */
 public void pausejob(string name, string group) throws schedulerexception {
  jobkey jobkey = new jobkey(name, group);
  jobdetail jobdetail = scheduler.getjobdetail(jobkey);
  if (jobdetail == null)
   return;
  scheduler.pausejob(jobkey);
 }

 /**
  * 恢复所有任务
  * 
  * @throws schedulerexception
  */
 public void resumealljob() throws schedulerexception {
  scheduler.resumeall();
 }

 /**
  * 恢复某个任务
  * 
  * @param name
  * @param group
  * @throws schedulerexception
  */
 public void resumejob(string name, string group) throws schedulerexception {
  jobkey jobkey = new jobkey(name, group);
  jobdetail jobdetail = scheduler.getjobdetail(jobkey);
  if (jobdetail == null)
   return;
  scheduler.resumejob(jobkey);
 }

 /**
  * 删除某个任务
  * 
  * @param name
  * @param group
  * @throws schedulerexception
  */
 public void deletejob(string name, string group) throws schedulerexception {
  jobkey jobkey = new jobkey(name, group);
  jobdetail jobdetail = scheduler.getjobdetail(jobkey);
  if (jobdetail == null)
   return;
  scheduler.deletejob(jobkey);
 }

完整代码

package com.yvan.quartz;

import java.util.date;

import org.quartz.cronschedulebuilder;
import org.quartz.crontrigger;
import org.quartz.jobbuilder;
import org.quartz.jobdetail;
import org.quartz.jobkey;
import org.quartz.scheduler;
import org.quartz.schedulerexception;
import org.quartz.triggerbuilder;
import org.quartz.triggerkey;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.configuration;

import com.yvan.quartz.job.schedulerquartzjob1;
import com.yvan.quartz.job.schedulerquartzjob2;
/**
 * 任务调度处理
 * @author yvan
 *
 */
@configuration
public class quartzscheduler {
 // 任务调度
 @autowired
 private scheduler scheduler;

 /**
  * 开始执行所有任务
  * 
  * @throws schedulerexception
  */
 public void startjob() throws schedulerexception {
  startjob1(scheduler);
  startjob2(scheduler);
  scheduler.start();
 }

 /**
  * 获取job信息
  * 
  * @param name
  * @param group
  * @return
  * @throws schedulerexception
  */
 public string getjobinfo(string name, string group) throws schedulerexception {
  triggerkey triggerkey = new triggerkey(name, group);
  crontrigger crontrigger = (crontrigger) scheduler.gettrigger(triggerkey);
  return string.format("time:%s,state:%s", crontrigger.getcronexpression(),
    scheduler.gettriggerstate(triggerkey).name());
 }

 /**
  * 修改某个任务的执行时间
  * 
  * @param name
  * @param group
  * @param time
  * @return
  * @throws schedulerexception
  */
 public boolean modifyjob(string name, string group, string time) throws schedulerexception {
  date date = null;
  triggerkey triggerkey = new triggerkey(name, group);
  crontrigger crontrigger = (crontrigger) scheduler.gettrigger(triggerkey);
  string oldtime = crontrigger.getcronexpression();
  if (!oldtime.equalsignorecase(time)) {
   cronschedulebuilder cronschedulebuilder = cronschedulebuilder.cronschedule(time);
   crontrigger trigger = triggerbuilder.newtrigger().withidentity(name, group)
     .withschedule(cronschedulebuilder).build();
   date = scheduler.reschedulejob(triggerkey, trigger);
  }
  return date != null;
 }

 /**
  * 暂停所有任务
  * 
  * @throws schedulerexception
  */
 public void pausealljob() throws schedulerexception {
  scheduler.pauseall();
 }

 /**
  * 暂停某个任务
  * 
  * @param name
  * @param group
  * @throws schedulerexception
  */
 public void pausejob(string name, string group) throws schedulerexception {
  jobkey jobkey = new jobkey(name, group);
  jobdetail jobdetail = scheduler.getjobdetail(jobkey);
  if (jobdetail == null)
   return;
  scheduler.pausejob(jobkey);
 }

 /**
  * 恢复所有任务
  * 
  * @throws schedulerexception
  */
 public void resumealljob() throws schedulerexception {
  scheduler.resumeall();
 }

 /**
  * 恢复某个任务
  * 
  * @param name
  * @param group
  * @throws schedulerexception
  */
 public void resumejob(string name, string group) throws schedulerexception {
  jobkey jobkey = new jobkey(name, group);
  jobdetail jobdetail = scheduler.getjobdetail(jobkey);
  if (jobdetail == null)
   return;
  scheduler.resumejob(jobkey);
 }

 /**
  * 删除某个任务
  * 
  * @param name
  * @param group
  * @throws schedulerexception
  */
 public void deletejob(string name, string group) throws schedulerexception {
  jobkey jobkey = new jobkey(name, group);
  jobdetail jobdetail = scheduler.getjobdetail(jobkey);
  if (jobdetail == null)
   return;
  scheduler.deletejob(jobkey);
 }

 private void startjob1(scheduler scheduler) throws schedulerexception {
  // 通过jobbuilder构建jobdetail实例,jobdetail规定只能是实现job接口的实例
  // jobdetail 是具体job实例
  jobdetail jobdetail = jobbuilder.newjob(schedulerquartzjob1.class).withidentity("job1", "group1").build();
  // 基于表达式构建触发器
  cronschedulebuilder cronschedulebuilder = cronschedulebuilder.cronschedule("0/5 * * * * ?");
  // crontrigger表达式触发器 继承于trigger
  // triggerbuilder 用于构建触发器实例
  crontrigger crontrigger = triggerbuilder.newtrigger().withidentity("job1", "group1")
    .withschedule(cronschedulebuilder).build();
  scheduler.schedulejob(jobdetail, crontrigger);
 }

 private void startjob2(scheduler scheduler) throws schedulerexception {
  jobdetail jobdetail = jobbuilder.newjob(schedulerquartzjob2.class).withidentity("job2", "group2").build();
  cronschedulebuilder cronschedulebuilder = cronschedulebuilder.cronschedule("0 0/5 * * * ?");
  crontrigger crontrigger = triggerbuilder.newtrigger().withidentity("job2", "group2")
    .withschedule(cronschedulebuilder).build();
  scheduler.schedulejob(jobdetail, crontrigger);
 }
}

scheduler 注入
这里采用监听spring容器加载完毕后事件,启动任务调用
将scheduler交给spring初始化管理

package com.yvan.quartz;

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(); 
 }

}

封装api
这里封装的api主要是为了方便动态管理执行任务,当然依赖这些接口也可以做一个界面来更直观的操作管理任务,这个就不再赘述。

package com.yvan.controller.quartzapi;

import org.quartz.schedulerexception;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

import com.yvan.quartz.quartzscheduler;

/**
 * 这里并没有采用restful风格 只是简单封装了一下api
 * 
 * @author yvan
 *
 */
@restcontroller
@requestmapping("/quartz")
public class quartzapicontroller {
 @autowired
 private quartzscheduler quartzscheduler;

 @requestmapping("/start")
 public void startquartzjob() {
  try {
   quartzscheduler.startjob();
  } catch (schedulerexception e) {
   e.printstacktrace();
  }
 }

 @requestmapping("/info")
 public string getquartzjob(string name, string group) {
  string info = null;
  try {
   info = quartzscheduler.getjobinfo(name, group);
  } catch (schedulerexception e) {
   e.printstacktrace();
  }
  return info;
 }

 @requestmapping("/modify")
 public boolean modifyquartzjob(string name, string group, string time) {
  boolean flag = true;
  try {
   flag = quartzscheduler.modifyjob(name, group, time);
  } catch (schedulerexception e) {
   e.printstacktrace();
  }
  return flag;
 }

 @requestmapping(value = "/pause")
 public void pausequartzjob(string name, string group) {
  try {
   quartzscheduler.pausejob(name, group);
  } catch (schedulerexception e) {
   e.printstacktrace();
  }
 }

 @requestmapping(value = "/pauseall")
 public void pauseallquartzjob() {
  try {
   quartzscheduler.pausealljob();
  } catch (schedulerexception e) {
   e.printstacktrace();
  }
 }

 @requestmapping(value = "/delete")
 public void deletejob(string name, string group) {
  try {
   quartzscheduler.deletejob(name, group);
  } catch (schedulerexception e) {
   e.printstacktrace();
  }
 }

}

运行结果

任务已经启动...
18-03-02 14:39:46,879  info tomcatembeddedservletcontainer:201 - tomcat started on port(s): 8080 (http)
-03-02 14:39:46,883  info start:57 - started start in 3.18 seconds (jvm running for 3.47)
任务开始执行
开始:1519972790003
结束:1519972790003
任务开始执行
任务开始执行
开始:1519972795000
结束:1519972795000
任务开始执行

以上所述是小编给大家介绍的springboot集成quartz动态定时任务详解整合,希望对大家有所帮助