Springboot Quartz定时任务的动态调度使用,实战详解,java教学管理系统的实现技术

  • Post author:
  • Post category:java

private Date updateTime; //更新时间

@Override

public String toString() {

return “JobEntity{” +

“jobId=’” + jobId + ‘’’ +

“, className=’” + className + ‘’’ +

“, cronExpression=’” + cronExpression + ‘’’ +

“, jobName=’” + jobName + ‘’’ +

“, jobGroup=’” + jobGroup + ‘’’ +

“, triggerName=’” + triggerName + ‘’’ +

“, triggerGroup=’” + triggerGroup + ‘’’ +

“, description=’” + description + ‘’’ +

“, data=” + data +

“, pauseStatus=” + pauseStatus +

“, deleteStatus=” + deleteStatus +

“, createTime=” + createTime +

“, updateTime=” + updateTime +

‘}’;

}

public String getJobId() {

return jobId;

}

public void setJobId(String jobId) {

this.jobId = jobId;

}

public String getClassName() {

return className;

}

public void setClassName(String className) {

this.className = className;

}

public String getCronExpression() {

return cronExpression;

}

public void setCronExpression(String cronExpression) {

this.cronExpression = cronExpression;

}

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 getTriggerName() {

return triggerName;

}

public void setTriggerName(String triggerName) {

this.triggerName = triggerName;

}

public String getTriggerGroup() {

return triggerGroup;

}

public void setTriggerGroup(String triggerGroup) {

this.triggerGroup = triggerGroup;

}

public String getDescription() {

return description;

}

public void setDescription(String description) {

this.description = description;

}

public JSONObject getData() {

return data;

}

public void setData(JSONObject data) {

this.data = data;

}

public Boolean getPauseStatus() {

return pauseStatus;

}

public void setPauseStatus(Boolean pauseStatus) {

this.pauseStatus = pauseStatus;

}

public Boolean getDeleteStatus() {

return deleteStatus;

}

public void setDeleteStatus(Boolean deleteStatus) {

this.deleteStatus = deleteStatus;

}

public Date getCreateTime() {

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

return createTime;

}

public void setCreateTime(Date createTime) {

this.createTime = createTime;

}

public Date getUpdateTime() {

return updateTime;

}

public void setUpdateTime(Date updateTime) {

this.updateTime = updateTime;

}

}

创建JobFactory.java (job实例工厂):

import org.quartz.spi.TriggerFiredBundle;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;

import org.springframework.scheduling.quartz.AdaptableJobFactory;

import org.springframework.stereotype.Component;

/**

  • @Author : JCccc

  • @CreateTime : 2020/3/21

  • @Description : 创建job实例工厂,使用默认的也许会出现spring的@Autowired 无法注入问题

**/

@Component

public class JobFactory extends AdaptableJobFactory {

@Autowired

private AutowireCapableBeanFactory beanFactory;

@Override

protected Object createJobInstance(TriggerFiredBundle bundle)

throws Exception {

Object jobInstance = super.createJobInstance(bundle);

//Job实例注入到Job工厂

beanFactory.autowireBean(jobInstance);

return jobInstance;

}

}

创建QuartzConfig.java (一些属性配置项):

import org.quartz.Scheduler;

import org.quartz.ee.servlet.QuartzInitializerListener;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.config.PropertiesFactoryBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;

import java.util.Properties;

/**

  • @Author : JCccc

  • @CreateTime : 2020/3/21

  • @Description : 调度工厂,线程池属性等等配置

**/

@Configuration

public class QuartzConfig {

@Autowired

private JobFactory jobFactory;

/**

  • 调度类FactoryBean

  • @return

  • @throws IOException

*/

@Bean(“schedulerFactory”)

public SchedulerFactoryBean schedulerFactoryBean() throws IOException {

SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();

//设置调度类quartz属性

schedulerFactoryBean.setQuartzProperties(quartzProperties());

//设置jobFactory

schedulerFactoryBean.setJobFactory(jobFactory);

return schedulerFactoryBean;

}

/**

  • 解析quartz.properties文件,填充属性

  • @return

  • @throws IOException

*/

@Bean

public Properties quartzProperties() throws IOException{

PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();

//若不做额外配置,会有默认的配置文件加载 在jar org.quartz里面 有一份quartz.properties

//propertiesFactoryBean.setLocation(new ClassPathResource(“/quartz.properties”));

propertiesFactoryBean.afterPropertiesSet();

return propertiesFactoryBean.getObject();

}

/**

  • quartz初始化监听器

  • @return

*/

@Bean

public QuartzInitializerListener initializerListener(){

return new QuartzInitializerListener();

}

/**

  • 根据调度类工厂bean获取调度

  • @return

  • @throws IOException

*/

@Bean(“scheduler”)

public Scheduler scheduler() throws IOException{

return schedulerFactoryBean().getScheduler();

}

}

ps:这里的配置项,特别是关于quartz的配置项,可以自己去写配置文件配置,但是该篇就使用默认的就够,默认的是jar包自己提供的:

简单瞅一眼:

相关参数什么作用,不懂的对着英文查询翻译即可,该篇不做展开。

接着,咱们实现一个调度方法类,类似于我们使用别的框架的Template一样。

新建QuartzService.java:

import com.alibaba.fastjson.JSONObject;

import com.bsapple.vshop.quartz.config.JobEntity;

/**

  • @Author : JCccc

  • @CreateTime : 2020/3/21

  • @Description :

**/

public interface QuartzService {

/**

  • 创建Job

  • @param job

*/

Boolean addJob(JobEntity job);

/**

  • 执行Job

  • @param job

*/

Boolean runJob(JobEntity job);

/**

  • 修改Job

  • @param job

*/

Boolean updateJob(JobEntity job);

/**

  • 暂定Job

  • @param job

*/

Boolean pauseJob(JobEntity job);

/**

  • 唤醒Job

  • @param job

*/

Boolean resumeJob(JobEntity job);

/**

  • 删除Job

  • @param job

*/

Boolean deleteJob(JobEntity job);

/**

  • 获取Job

  • @param job

*/

JSONObject queryJob(JobEntity job);

}

对应的impl,QuartzServiceImpl.java:

import com.alibaba.fastjson.JSONObject;

import com.bsapple.vshop.quartz.config.JobEntity;

import org.quartz.*;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.stereotype.Service;

/**

  • @Author : JCccc

  • @CreateTime : 2020/3/21

  • @Description :

**/

@Service

public class QuartzServiceImpl implements QuartzService {

private static Logger log = LoggerFactory.getLogger(QuartzServiceImpl.class);

@Autowired

@Qualifier(“scheduler”)

private Scheduler scheduler;

@Override

public Boolean addJob(JobEntity job) {

try {

JSONObject data = job.getData();

log.info(“当前任务携带的业务参数={}”, data.toJSONString());

JobDataMap jobDataMap = new JobDataMap();

jobDataMap.put(“myValue”, data);

String jobId = job.getJobId();

String jobName = job.getJobName();

String jobUnique = jobId + jobName;

JobDetail jobDetail = JobBuilder

.newJob((Class<? extends Job>) Class.forName(job.getClassName()))

// 指定执行类

.withIdentity(jobUnique, job.getJobGroup())

// 指定name和group

.requestRecovery().withDescription(job.getDescription())

.setJobData(jobDataMap)

.build();

// 创建表达式调度构建器

CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder

.cronSchedule(job.getCronExpression());

// 创建触发器

CronTrigger cronTrigger = TriggerBuilder.newTrigger()

.withIdentity(job.getTriggerName(), job.getTriggerGroup())

.withDescription(job.getDescription())

.withSchedule(cronScheduleBuilder).build();

scheduler.scheduleJob(jobDetail, cronTrigger);

scheduler.start();

log.info(“定时任务[{}]创建成功,开始执行”, jobId + jobName);

return true;

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

@Override

public Boolean runJob(JobEntity job) {

try {

String jobId = job.getJobId();

String jobName = job.getJobName();

String jobUnique = jobId + jobName;

scheduler.triggerJob(JobKey.jobKey(jobUnique,

job.getJobGroup()));

log.info(“定时任务[{}]执行成功”, jobUnique);

return true;

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

@Override

public Boolean updateJob(JobEntity job) {

try {

String jobId = job.getJobId();

String jobName = job.getJobName();

String jobUnique = jobId + jobName;

TriggerKey triggerKey = new TriggerKey(job.getTriggerName(),

job.getTriggerGroup());

CronTrigger cronTrigger = (CronTrigger) scheduler

.getTrigger(triggerKey);

CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder

.cronSchedule(job.getCronExpression());

// 重新构件表达式

CronTrigger trigger = cronTrigger.getTriggerBuilder()

.withIdentity(triggerKey).withSchedule(cronScheduleBuilder)

.withDescription(job.getDescription())

.build();

scheduler.rescheduleJob(triggerKey, trigger);

log.info(“定时任务[{}]更新成功”, jobUnique);

return true;

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

@Override

public Boolean pauseJob(JobEntity job) {

try {

String jobId = job.getJobId();

String jobName = job.getJobName();

String jobUnique = jobId + jobName;

scheduler.pauseJob(JobKey.jobKey(jobUnique,

job.getJobGroup()));

log.info(“定时任务[{}]暂停成功”, jobUnique);

return true;

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

@Override

public Boolean resumeJob(JobEntity job) {

try {

String jobId = job.getJobId();

String jobName = job.getJobName();

String jobUnique = jobId + jobName;

scheduler.resumeJob(JobKey.jobKey(jobUnique,

job.getJobGroup()));

log.info(“定时任务[{}]唤醒成功”, jobUnique);

return true;

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

@Override

public Boolean deleteJob(JobEntity job) {

try {

String jobId = job.getJobId();

String jobName = job.getJobName();

String jobUnique = jobId + jobName;

scheduler.deleteJob(JobKey.jobKey(jobUnique, job.getJobGroup()));

log.info(“定时任务[{}]删除成功”, jobUnique);

return true;

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

@Override

public JSONObject queryJob(JobEntity job) {

TriggerKey triggerKey = new TriggerKey(job.getTriggerName(),

job.getTriggerGroup());

try {

CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);

if (null == cronTrigger) {

return null;

}

JSONObject jsonObject = new JSONObject();

jsonObject.put(“expression”, cronTrigger.getCronExpression());

jsonObject.put(“state”, scheduler.getTriggerState(triggerKey));

jsonObject.put(“description”, cronTrigger.getDescription());

return jsonObject;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}

到这,其实动态的调度定时任务条件,我们都已经准备充分了。

接下来是使用环节:


1.随着项目启动就启动的定时任务


之所以能随着项目启动就跟着启动,那么显然,就跟监听项目启动有关系。

创建MyJobAuto.java ,继承job,做为定时任务示例:

/**

  • @Author : JCccc

  • @CreateTime : 2020/3/21

  • @Description :

**/

import com.alibaba.fastjson.JSONObject;

import org.quartz.Job;

import org.quartz.JobDataMap;

import org.quartz.JobExecutionContext;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

@Component

public class MyJobAuto implements Job {

private static Logger log = LoggerFactory.getLogger(MyJobAuto.class);

private void before() {

log.info(“MyJobAuto任务开始执行”);

}

@Override

public void execute(JobExecutionContext context) {

before();

//定时任务处理的业务逻辑

//…

//…

String name = context.getJobDetail().getKey().getName();

log.info(“MyJobAuto任务[{}]正在执行”,name);

JobDataMap jobDataMap=context.getJobDetail().getJobDataMap();

JSONObject jsonObject = (JSONObject) jobDataMap.get(“myValue”);

log.info(“MyJobAuto任务[{}]携带的参数[{}]”,name,jsonObject.toString());

String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”));

log.info(“当前时间[{}],MyJobAuto任务[{}]的线程名[{}]”,time,name,Thread.currentThread().getName());

after();

}

private void after() {

log.info(“MyJobAuto任务执行结束”);

}

}

然后是项目启动监听器,创建ApplicationStartListener.java:

import com.alibaba.fastjson.JSONObject;

import com.bsapple.vshop.quartz.config.JobEntity;

import com.bsapple.vshop.quartz.jobManage.QuartzService;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationListener;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.event.ContextRefreshedEvent;

import java.util.UUID;

/**

  • @Author : JCccc

  • @CreateTime : 2020/3/21

  • @Description :

**/

@Configuration

public class ApplicationStartListener implements ApplicationListener {

private static Logger log = LoggerFactory.getLogger(ApplicationStartListener.class);

@Autowired

private QuartzService quartzService;

@Override

public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

JobEntity job=new JobEntity();

job.setJobId(UUID.randomUUID().toString().replaceAll(“-“,””));

job.setClassName(“com.bsapple.vshop.quartz.taskJob.MyJobAuto”);//注意,这里的路径请改成你自己的

job.setCronExpression(“0/3 * * * * ?”);

job.setJobName(“AutoJob”);

job.setJobGroup(“AutoJobGroup”);

job.setTriggerName(“AutoJobTrigger”);

job.setTriggerGroup(“AutoJobTriggerGroup”);

job.setDescription(“AutoJob-随项目启动”);

//可以将任务跟数据库挂钩,做个任务管理模块,获取需要自启动的任务,记录各个参数等

JSONObject jsonObject=new JSONObject();

jsonObject.put(“testKey”,“测试即启动”);

job.setData(jsonObject);

quartzService.addJob(job);

log.info(“即触发定时任务已经开始执行… .”);

log.info(“application已经启动完毕”);

}

}

事不宜迟,先把项目启动起来看看效果,成功执行,根据cron表达式,3秒一次:

再看一眼线程名里面,可以看到quartz加载了默认配置,线程数量10:

2.动态调度定时任务


我们在前面已经把调度方法的模版已经写了,那么实现调度场景就非常简单了。

创建QuartzController.java:

import com.alibaba.fastjson.JSONObject;

import com.bsapple.vshop.quartz.config.JobEntity;

import com.bsapple.vshop.quartz.jobManage.QuartzService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

/**

  • @Author : JCccc

  • @CreateTime : 2020/3/21

  • @Description :

**/

@RestController

@RequestMapping(“/quartz”)

public class QuartzController {

@Autowired

private QuartzService quartzService;

@PostMapping(“/add”)

public String addJob(@RequestBody JobEntity job) {

Boolean result = quartzService.addJob(job);

if (!result) {

return “创建定时任务失败”;

}

return “创建定时任务成功:”+job.getJobId()+job.getJobName();

}

@PostMapping(“/run”)

public String runJob(@RequestBody JobEntity job) {

Boolean result = quartzService.runJob(job);

if (!result) {

return “启动定时任务失败”;

}

return “启动定时任务成功:”+job.getJobId()+job.getJobName();

}

@PostMapping(“/update”)

public String updateJob(@RequestBody JobEntity job) {

Boolean result = quartzService.updateJob(job);

if (!result) {

return “修改定时任务失败”;

}

return “修改定时任务成功:”+job.getJobId()+job.getJobName();

}

@PostMapping(“/pause”)

public String pauseJob(@RequestBody JobEntity job) {

Boolean result = quartzService.pauseJob(job);

if (!result) {

return “暂停定时任务失败”;

}

return “暂停定时任务成功:”+job.getJobId()+job.getJobName();

}

@PostMapping(“/resume”)

public String resumeJob(@RequestBody JobEntity job) {

Boolean result = quartzService.resumeJob(job);

if (!result) {

return “唤醒定时任务失败”;

}

return “唤醒定时任务成功:”+job.getJobId()+job.getJobName();

}

@PostMapping(“/delete”)

public String deleteJob(@RequestBody JobEntity job) {

Boolean result = quartzService.deleteJob(job);

if (!result) {

return “删除定时任务失败”;

}

return “删除定时任务成功:”+job.getJobId()+job.getJobName();

}

@GetMapping(“/query”)

public String queryJob(@RequestBody JobEntity job) {

JSONObject result = quartzService.queryJob(job);

if (null == result) {

return “不存在对应的任务:”+job.getJobId()+job.getJobName();

}

return result.toString();

}

}


版权声明:本文为m0_54865014原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。