如题:

首先贴上maven的配置

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>

再贴上两个要用的实体类

package com.hw.domain;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.io.Serializable;

@SuppressWarnings("serial")
public class ScheduleJob implements Serializable ,Job {

public static final String STATUS_RUNNING = "1";
public static final String STATUS_NOT_RUNNING = "0";
public static final String CONCURRENT_IS = "1";
public static final String CONCURRENT_NOT = "0";

/**
* 任务名称
*/
private String jobName;
/**
* 任务分组
*/
private String jobGroup;
/**
* 任务状态 是否启动任务
*/
private String jobStatus;
/**
* cron表达式
*/
private String cronExpression;
/**
* 描述
*/
private String description;
/**
* 任务执行时调用哪个类的方法 包名+类名
*/
private String beanClass;
/**
* 任务是否有状态
*/
private String isConcurrent;

/**
* Spring bean
*/
private String springBean;

/**
* 任务调用的方法名
*/
private String methodName;

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 getJobStatus() {
return jobStatus;
}

public void setJobStatus(String jobStatus) {
this.jobStatus = jobStatus;
}

public String getCronExpression() {
return cronExpression;
}

public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public String getBeanClass() {
return beanClass;
}

public void setBeanClass(String beanClass) {
this.beanClass = beanClass;
}

public String getIsConcurrent() {
return isConcurrent;
}

public void setIsConcurrent(String isConcurrent) {
this.isConcurrent = isConcurrent;
}

public String getMethodName() {
return methodName;
}

public void setMethodName(String methodName) {
this.methodName = methodName;
}

public String getSpringBean() {
return springBean;
}

public void setSpringBean(String springBean) {
this.springBean = springBean;
}

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// TODO Auto-generated method stub

}


}

















package com.hw.domain;

import java.io.Serializable;
import java.util.Date;


public class TaskDO implements Serializable {
private static final long serialVersionUID = 1L;

//
private Long id;
// cron表达式
private String cronExpression;
// 任务调用的方法名
private String methodName;
// 任务是否有状态
private String isConcurrent;
// 任务描述
private String description;
// 更新者
private String updateBy;
// 任务执行时调用哪个类的方法 包名+类名
private String beanClass;
// 创建时间
private Date createDate;
// 任务状态
private String jobStatus;
// 任务分组
private String jobGroup;
// 更新时间
private Date updateDate;
// 创建者
private String createBy;
// Spring bean
private String springBean;
// 任务名
private String jobName;

/**
* 设置:
*/
public void setId(Long id) {
this.id = id;
}

/**
* 获取:
*/
public Long getId() {
return id;
}

/**
* 设置:cron表达式
*/
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}

/**
* 获取:cron表达式
*/
public String getCronExpression() {
return cronExpression;
}

/**
* 设置:任务调用的方法名
*/
public void setMethodName(String methodName) {
this.methodName = methodName;
}

/**
* 获取:任务调用的方法名
*/
public String getMethodName() {
return methodName;
}

/**
* 设置:任务是否有状态
*/
public void setIsConcurrent(String isConcurrent) {
this.isConcurrent = isConcurrent;
}

/**
* 获取:任务是否有状态
*/
public String getIsConcurrent() {
return isConcurrent;
}

/**
* 设置:任务描述
*/
public void setDescription(String description) {
this.description = description;
}

/**
* 获取:任务描述
*/
public String getDescription() {
return description;
}

/**
* 设置:更新者
*/
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}

/**
* 获取:更新者
*/
public String getUpdateBy() {
return updateBy;
}

/**
* 设置:任务执行时调用哪个类的方法 包名+类名
*/
public void setBeanClass(String beanClass) {
this.beanClass = beanClass;
}

/**
* 获取:任务执行时调用哪个类的方法 包名+类名
*/
public String getBeanClass() {
return beanClass;
}

/**
* 设置:创建时间
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}

/**
* 获取:创建时间
*/
public Date getCreateDate() {
return createDate;
}

/**
* 设置:任务状态
*/
public void setJobStatus(String jobStatus) {
this.jobStatus = jobStatus;
}

/**
* 获取:任务状态
*/
public String getJobStatus() {
return jobStatus;
}

/**
* 设置:任务分组
*/
public void setJobGroup(String jobGroup) {
this.jobGroup = jobGroup;
}

/**
* 获取:任务分组
*/
public String getJobGroup() {
return jobGroup;
}

/**
* 设置:更新时间
*/
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}

/**
* 获取:更新时间
*/
public Date getUpdateDate() {
return updateDate;
}

/**
* 设置:创建者
*/
public void setCreateBy(String createBy) {
this.createBy = createBy;
}

/**
* 获取:创建者
*/
public String getCreateBy() {
return createBy;
}

/**
* 设置:Spring bean
*/
public void setSpringBean(String springBean) {
this.springBean = springBean;
}

/**
* 获取:Spring bean
*/
public String getSpringBean() {
return springBean;
}

/**
* 设置:任务名
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}

/**
* 获取:任务名
*/
public String getJobName() {
return jobName;
}

@Override
public String toString() {
return "TaskDO{" +
"id=" + id +
", cronExpression='" + cronExpression + '\'' +
", methodName='" + methodName + '\'' +
", isConcurrent='" + isConcurrent + '\'' +
", description='" + description + '\'' +
", updateBy='" + updateBy + '\'' +
", beanClass='" + beanClass + '\'' +
", createDate=" + createDate +
", jobStatus='" + jobStatus + '\'' +
", jobGroup='" + jobGroup + '\'' +
", updateDate=" + updateDate +
", createBy='" + createBy + '\'' +
", springBean='" + springBean + '\'' +
", jobName='" + jobName + '\'' +
'}';
}
}

dao层和mybatis的配置crud就不贴了 就简单的增删改查,重点是得和quartz整合

再贴上quartz的两个配置类

package com.hw.quartz.factory;

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;

@Component
public class JobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;

@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
//调用父类的方法
Object jobInstance = super.createJobInstance(bundle);
//进行注入
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}



















package com.hw.quartz.utils;


import com.hw.domain.ScheduleJob;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.DateBuilder;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
*
*
* @title: QuartzManager.java
* @description: 计划任务管理
*
*/
@Service
public class QuartzManager {
public final Logger log = LoggerFactory.getLogger(QuartzManager.class);
// private SchedulerFactoryBean schedulerFactoryBean
// =SpringContextHolder.getBean(SchedulerFactoryBean.class);
// @Autowired
// @Qualifier("schedulerFactoryBean")
// private SchedulerFactoryBean schedulerFactoryBean;
@Autowired
private Scheduler scheduler;

/**
* 添加任务
*
* @throws SchedulerException
*/

public void addJob(ScheduleJob job) {
try {
// 创建jobDetail实例,绑定Job实现类
// 指明job的名称,所在组的名称,以及绑定job类

Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(job.getBeanClass()).newInstance()
.getClass());
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getJobName(), job.getJobGroup())// 任务名称和组构成任务key
.build();
// 定义调度触发规则
// 使用cornTrigger规则
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())// 触发器key
.startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
.withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression())).startNow().build();
// 把作业和触发器注册到任务调度中
scheduler.scheduleJob(jobDetail, trigger);
// 启动
if (!scheduler.isShutdown()) {
scheduler.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 获取所有计划中的任务列表
*
* @return
* @throws SchedulerException
*/
public List<ScheduleJob> getAllJob() throws SchedulerException {
GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
for (JobKey jobKey : jobKeys) {
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
for (Trigger trigger : triggers) {
ScheduleJob job = new ScheduleJob();
job.setJobName(jobKey.getName());
job.setJobGroup(jobKey.getGroup());
job.setDescription("触发器:" + trigger.getKey());
Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
job.setJobStatus(triggerState.name());
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String cronExpression = cronTrigger.getCronExpression();
job.setCronExpression(cronExpression);
}
jobList.add(job);
}
}
return jobList;
}

/**
* 所有正在运行的job
*
* @return
* @throws SchedulerException
*/
public List<ScheduleJob> getRunningJob() throws SchedulerException {
List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
List<ScheduleJob> jobList = new ArrayList<ScheduleJob>(executingJobs.size());
for (JobExecutionContext executingJob : executingJobs) {
ScheduleJob job = new ScheduleJob();
JobDetail jobDetail = executingJob.getJobDetail();
JobKey jobKey = jobDetail.getKey();
Trigger trigger = executingJob.getTrigger();
job.setJobName(jobKey.getName());
job.setJobGroup(jobKey.getGroup());
job.setDescription("触发器:" + trigger.getKey());
Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
job.setJobStatus(triggerState.name());
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String cronExpression = cronTrigger.getCronExpression();
job.setCronExpression(cronExpression);
}
jobList.add(job);
}
return jobList;
}

/**
* 暂停一个job
*
* @param scheduleJob
* @throws SchedulerException
*/
public void pauseJob(ScheduleJob scheduleJob) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
scheduler.pauseJob(jobKey);
}

/**
* 恢复一个job
*
* @param scheduleJob
* @throws SchedulerException
*/
public void resumeJob(ScheduleJob scheduleJob) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
scheduler.resumeJob(jobKey);
}

/**
* 删除一个job
*
* @param scheduleJob
* @throws SchedulerException
*/
public void deleteJob(ScheduleJob scheduleJob) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
scheduler.deleteJob(jobKey);

}

/**
* 立即执行job
*
* @param scheduleJob
* @throws SchedulerException
*/
public void runAJobNow(ScheduleJob scheduleJob) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
scheduler.triggerJob(jobKey);
}

/**
* 更新job时间表达式
*
* @param scheduleJob
* @throws SchedulerException
*/
public void updateJobCron(ScheduleJob scheduleJob) throws SchedulerException {

TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());

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

CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());

trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

scheduler.rescheduleJob(triggerKey, trigger);
}
}

两个帮助方法类

package com.hw.utils;

public class Constant {
//演示系统账户
public static String DEMO_ACCOUNT = "test";
//自动去除表前缀
public static String AUTO_REOMVE_PRE = "true";
//停止计划任务
public static String STATUS_RUNNING_STOP = "stop";
//开启计划任务
public static String STATUS_RUNNING_START = "start";
//通知公告阅读状态-未读
public static String OA_NOTIFY_READ_NO = "0";
//通知公告阅读状态-已读
public static int OA_NOTIFY_READ_YES = 1;
//部门根节点id
public static Long DEPT_ROOT_ID = 0l;
//缓存方式
public static String CACHE_TYPE_REDIS ="redis";

public static String LOG_ERROR = "error";


}












package com.hw.utils;


import com.hw.domain.ScheduleJob;
import com.hw.domain.TaskDO;

public class ScheduleJobUtils {
public static ScheduleJob entityToData(TaskDO scheduleJobEntity) {
ScheduleJob scheduleJob = new ScheduleJob();
scheduleJob.setBeanClass(scheduleJobEntity.getBeanClass());
scheduleJob.setCronExpression(scheduleJobEntity.getCronExpression());
scheduleJob.setDescription(scheduleJobEntity.getDescription());
scheduleJob.setIsConcurrent(scheduleJobEntity.getIsConcurrent());
scheduleJob.setJobName(scheduleJobEntity.getJobName());
scheduleJob.setJobGroup(scheduleJobEntity.getJobGroup());
scheduleJob.setJobStatus(scheduleJobEntity.getJobStatus());
scheduleJob.setMethodName(scheduleJobEntity.getMethodName());
scheduleJob.setSpringBean(scheduleJobEntity.getSpringBean());
return scheduleJob;
}
}

service层的实现类代码贴上

package com.hw.service.impl;

import com.hw.dao.TaskDao;
import com.hw.domain.ScheduleJob;
import com.hw.domain.TaskDO;
import com.hw.quartz.utils.QuartzManager;
import com.hw.service.JobService;
import com.hw.utils.Constant;
import com.hw.utils.ScheduleJobUtils;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JobServiceImpl implements JobService {

@Autowired
private TaskDao taskScheduleJobMapper;

@Autowired
QuartzManager quartzManager;

@Override
public TaskDO get(Long id) {
return taskScheduleJobMapper.get(id);
}

@Override
public List<TaskDO> list(Map<String, Object> map) {
return taskScheduleJobMapper.list(map);
}

@Override
public int count(Map<String, Object> map) {
return taskScheduleJobMapper.count(map);
}

@Override
public int save(TaskDO taskScheduleJob) {
return taskScheduleJobMapper.save(taskScheduleJob);
}

@Override
public int update(TaskDO taskScheduleJob) {
return taskScheduleJobMapper.update(taskScheduleJob);
}

@Override
public int remove(Long id) {
try {
TaskDO scheduleJob = get(id);
quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
return taskScheduleJobMapper.remove(id);
} catch (SchedulerException e) {
e.printStackTrace();
return 0;
}

}

@Override
public int batchRemove(Long[] ids) {
for (Long id : ids) {
try {
TaskDO scheduleJob = get(id);
quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
} catch (SchedulerException e) {
e.printStackTrace();
return 0;
}
}
return taskScheduleJobMapper.batchRemove(ids);
}

@Override
public void initSchedule() throws SchedulerException {
// 这里获取任务信息数据
List<TaskDO> jobList = taskScheduleJobMapper.list(new HashMap<String, Object>(16));
for (TaskDO scheduleJob : jobList) {
if ("1".equals(scheduleJob.getJobStatus())) {
ScheduleJob job = ScheduleJobUtils.entityToData(scheduleJob);
quartzManager.addJob(job);
}

}
}

@Override
public void changeStatus(Long jobId, String cmd) throws SchedulerException {
TaskDO scheduleJob = get(jobId);
if (scheduleJob == null) {
return;
}
if (Constant.STATUS_RUNNING_STOP.equals(cmd)) {
quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
scheduleJob.setJobStatus(ScheduleJob.STATUS_NOT_RUNNING);
} else {
if (!Constant.STATUS_RUNNING_START.equals(cmd)) {
} else {
scheduleJob.setJobStatus(ScheduleJob.STATUS_RUNNING);
quartzManager.addJob(ScheduleJobUtils.entityToData(scheduleJob));
}
}
update(scheduleJob);
}

@Override
public void updateCron(Long jobId) throws SchedulerException {
TaskDO scheduleJob = get(jobId);
if (scheduleJob == null) {
return;
}
if (ScheduleJob.STATUS_RUNNING.equals(scheduleJob.getJobStatus())) {
quartzManager.updateJobCron(ScheduleJobUtils.entityToData(scheduleJob));
}
update(scheduleJob);
}

}

测试案例需要的controller

package com.hw.controller;



import com.hw.domain.TaskDO;
import com.hw.service.JobService;
import com.hw.utils.Constant;
import com.hw.utils.R;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/common/job")
public class JobController{
@Autowired
private JobService taskScheduleJobService;

@GetMapping()
String taskScheduleJob() {
return "common/job/job";
}

@ResponseBody
@GetMapping("/list")
public List<TaskDO> list(@RequestParam Map<String, Object> params) {
// 查询列表数据
List<TaskDO> taskScheduleJobList = taskScheduleJobService.list(null);
return taskScheduleJobList;
}

@GetMapping("/add")
String add() {
return "common/job/add";
}

@GetMapping("/edit/{id}")
String edit(@PathVariable("id") Long id, Model model) {
TaskDO job = taskScheduleJobService.get(id);
model.addAttribute("job", job);
return "common/job/edit";
}

/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id) {
TaskDO taskScheduleJob = taskScheduleJobService.get(id);
return R.ok().put("taskScheduleJob", taskScheduleJob);
}

/**
* 保存
*/
@ResponseBody
@PostMapping("/save")
public R save(TaskDO taskScheduleJob) {

if (taskScheduleJobService.save(taskScheduleJob) > 0) {
return R.ok();
}
return R.error();
}

/**
* 修改
*/
@ResponseBody
@PostMapping("/update")
public R update(TaskDO taskScheduleJob) {

taskScheduleJobService.update(taskScheduleJob);
return R.ok();
}

/**
* 删除
*/
@PostMapping("/remove")
@ResponseBody
public R remove(Long id) {

if (taskScheduleJobService.remove(id) > 0) {
return R.ok();
}
return R.error();
}

/**
* 删除
*/
@PostMapping("/batchRemove")
@ResponseBody
public R remove(@RequestParam("ids[]") Long[] ids) {

taskScheduleJobService.batchRemove(ids);

return R.ok();
}

@PostMapping(value = "/changeJobStatus")
@ResponseBody
public R changeJobStatus(Long id,String cmd ) {
String label = "停止";
if ("start".equals(cmd)) {
label = "启动";
} else {
label = "停止";
}
try {
taskScheduleJobService.changeStatus(id, cmd);
return R.ok("任务" + label + "成功");
} catch (Exception e) {
e.printStackTrace();
}
return R.ok("任务" + label + "失败");
}

}

好,最后贴上咱们执行定时任务的类   完事开始测试案例

package com.hw.task;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.DateUtils;

import java.util.Random;

/**
* @program: bootdo-job
* @description:
* @author: hw
* @create: 2019-09-14 14:28
**/
@Component
public class test implements Job {
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {

System.err.println(new Random().nextInt()+"---"+ System.currentTimeMillis()/1000);
}
}

springboot整合quartz达到动态配置定时任务的效果_方法名

然后咱们停止后修改一下cron表达式然后再启动(贴上生成网址:​http://cron.qqe2.com/​)

springboot整合quartz达到动态配置定时任务的效果_springboot整合quartz_02

springboot整合quartz达到动态配置定时任务的效果_类名_03

springboot整合quartz达到动态配置定时任务的效果_类名_04

springboot整合quartz达到动态配置定时任务的效果_spring_05