提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、pom的配置
- 1.加注解
- 二、使用方法
- 1.工程图
- 2.创建工具类
- 三、controller 实现
前言
提示:这里可以添加本文要记录的大概内容:
提示:以下是本篇文章正文内容,下面案例可供参考
一、pom的配置
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
1.加注解
@EnableScheduling
public class BusinessApplication {
public static void main(String[] args) {
SpringApplication.run(BusinessApplication.class, args);
log.info("*********启动成功************");
}
}
二、使用方法
1.工程图
2.创建工具类
package com.juyuan.api.scheduled_tasks.pojo;
import lombok.Data;
@Data
public class QuartzBean {
//任务名称
private String jobID ;
//执行任务类
private String jobClass;
//cron表达式
private String cron;
}
package com.juyuan.api.scheduled_tasks.jop;
import org.quartz.*;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
public class SimpleTask extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException{
JobDetail jobDetail = jobExecutionContext.getJobDetail();
JobKey key = jobDetail.getKey();
System. out.println("任务名称为:"+key.getName()+",执行时间为:"+ LocalDateTime.now());
System.out.println("=======================添加数据===================================");
}
}
package com.juyuan.api.scheduled_tasks.utils;
import com.juyuan.api.scheduled_tasks.pojo.QuartzBean;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
public class QuartzUtils {
/*
*创建定时任务
*@param scheduler 调度器
*@param quartzBean 定时任务信息类
*/
@Bean
public static void createScheduleJob(Scheduler scheduler, QuartzBean quartzBean){
try {
Class<? extends Job> aClass = (Class<? extends Job>) Class.forName(quartzBean.getJobClass());
JobDetail build = JobBuilder.newJob(aClass).withIdentity(quartzBean.getJobID()).build();
//表达式调度构建器
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCron());
//按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(quartzBean.getJobID()).withSchedule(cronScheduleBuilder).build();
scheduler.scheduleJob(build,trigger);
} catch (ClassNotFoundException | SchedulerException e) {
throw new RuntimeException(e);
}
}
/*根据任务恢复定时任务
@param scheduler 调度器
任务名称* param jobName
*/
public static void resumeScheduleJob(Scheduler scheduler, String jobName) {
JobKey jobKey = JobKey.jobKey(jobName);
try {
scheduler.resumeJob(jobKey);
} catch (SchedulerException e) {
throw new RuntimeException("恢复定时任务失败" + e.getMessage());
}
}
/**
* 暂停定时任务
*/
public static void pauseScheduleJob(Scheduler scheduler, String jobName) {
JobKey jobKey = JobKey.jobKey(jobName);
try {
scheduler.pauseJob(jobKey);
} catch (SchedulerException e) {
throw new RuntimeException("暂停定时任务失败" + e.getMessage());
}
}
/**
* 立即执行定时任务
*/
public static void runScheduleJob(Scheduler scheduler, String jobName) {
JobKey jobKey = JobKey.jobKey(jobName);
try {
scheduler.triggerJob(jobKey);
} catch (SchedulerException e) {
throw new RuntimeException("立即执行定时任务失败" + e.getMessage());
}
}
/**
* 删除定时任务
*/
public static void deleteScheduleJob(Scheduler scheduler, String jobName) {
JobKey jobKey = JobKey.jobKey(jobName);
try {
scheduler.deleteJob(jobKey);
} catch (SchedulerException e) {
throw new RuntimeException("删除定时任务失败" + e.getMessage());
}
}
/**
* 获取所有定时任务
*
* @param scheduler 调度器
* @return 返回所有定时任务列表
*/
public static List<JobDetail> getAllScheduleJob(Scheduler scheduler) {
try {
// 获取所有的JobKeys
Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());
// 创建一个列表来存储所有的JobDetail对象
List<JobDetail> jobDetails = new ArrayList<>();
// 遍历每个JobKey,获取对应的JobDetail
for (JobKey jobKey : jobKeys) {
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
jobDetails.add(jobDetail);
}
// 现在,jobDetails列表包含了所有的JobDetail对象
// 您可以在这里对这些对象进行处理
return jobDetails;
} catch (SchedulerException e) {
throw new RuntimeException("获取所有定时任务失败" + e.getMessage());
}
}
/**
* 获取所有正在运行的定时任务
*
* @param scheduler 调度器
* @return 返回所有正在运行的定时任务列表
*/
public static List<JobDetail> getRunningScheduleJob(Scheduler scheduler) {
try {
List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
List<JobDetail> jobDetails = new ArrayList<>();
for (JobExecutionContext executingJob : executingJobs) {
JobDetail jobDetail = executingJob.getJobDetail();
jobDetails.add(jobDetail);
}
return jobDetails;
} catch (SchedulerException e) {
throw new RuntimeException("获取所有正在运行的定时任务失败" + e.getMessage());
}
}
/**
* 修改定时任务
* @param scheduler 调度器
*/
public static void updateScheduleJob(Scheduler scheduler, QuartzBean quartzBean) {
//获取对应的jobKey
TriggerKey triggerKey = TriggerKey.triggerKey(quartzBean.getJobID());
//获取执行定时任务的执行方式
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCron());
try {
//按新的cronExpression表达式重新构建trigger
CronTrigger character= (CronTrigger)scheduler.getTrigger(triggerKey);
character = character.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
//按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, character);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
}
三、controller 实现
package com.juyuan.api.scheduled_tasks.controller;
import com.juyuan.api.park_enterprise_public_construction.entity.ActionPlan;
import com.juyuan.api.park_enterprise_public_construction.service.ActionPlanService;
import com.juyuan.api.scheduled_tasks.pojo.QuartzBean;
import com.juyuan.api.scheduled_tasks.utils.QuartzUtils;
import com.juyuan.framework.common.constants.WebConstant;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class QuartzBeanController {
private final String PATH = WebConstant.API_PATH + "/quartz/";
@Autowired
private Scheduler scheduler;
@Autowired
private ActionPlanService actionPlanService;
//新增执行定时任务
@GetMapping(value = PATH + "add")
public void add() {
List<ActionPlan> list = actionPlanService.list();
for (ActionPlan actionPlan : list) {
QuartzBean quartzBean = new QuartzBean();
quartzBean.setJobID(actionPlan.getId());
quartzBean.setJobClass("com.juyuan.api.scheduled_tasks.jop.SimpleTask");
quartzBean.setCron(actionPlan.getFrequency());
QuartzUtils.createScheduleJob(scheduler,quartzBean);
}
}
//暂停执行定时任务
@GetMapping(value = PATH + "pause")
public void pause() {
QuartzUtils.pauseScheduleJob(scheduler,"2");
}
//恢复执行定时任务
@GetMapping(value = PATH + "resume")
public void resume() {
QuartzUtils.resumeScheduleJob(scheduler,"1");
}
//删除执行定时任务
@GetMapping(value = PATH + "delete")
public void delete() {
QuartzUtils.deleteScheduleJob(scheduler,"2");
}
//立即执行定时任务
@GetMapping(value = PATH + "run")
public void run() {
QuartzUtils.runScheduleJob(scheduler,"2");
}
//获取所有定时任务
// 获取所有定时任务的接口
@GetMapping(value = PATH + "queryAll")
public void queryAll() {
// 获取所有定时任务列表
List<JobDetail> allScheduleJob = QuartzUtils.getAllScheduleJob(scheduler);
// 遍历所有定时任务
allScheduleJob.forEach(jobDetail -> {
// 打印任务名称
System.out.println(jobDetail.getKey().getName());
// 打印任务组名
// System.out.println(jobDetail.getKey().getGroup());
// 打印任务描述
// System.out.println(jobDetail.getDescription());
// 打印任务类名
// System.out.println(jobDetail.getJobClass());
// 打印任务数据映射
// System.out.println(jobDetail.getJobDataMap());
});
}
//修改执行定时任务
@GetMapping(value = PATH + "update")
public void update() {
QuartzBean quartzBean = new QuartzBean();
quartzBean.setCron("0/5 * * * *?");
quartzBean.setJobID("2");
QuartzUtils.updateScheduleJob(scheduler,quartzBean);
}
}