1 Maven依赖
<!--hutool工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.1</version>
</dependency>
<!--quartz定时任务-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
2 调试代码
package com.controller;
import cn.hutool.core.date.DateUtil;
import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/quartz")
public class QuartzController {
@Autowired
private SchedulerFactoryBean schedulerFactoryBean;
/**
* 获取所有定时任务
*
* @return
*/
@GetMapping("/getJobList")
public List<Map<String, String>> getJobList() {
List<Map<String, String>> jobList = new ArrayList<>();
try {
//获取Scheduler
Scheduler scheduler = schedulerFactoryBean.getScheduler();
//再获取Scheduler下的所有group
List<String> triggerGroupNames = scheduler.getTriggerGroupNames();
for (String groupName : triggerGroupNames) {
//组装group的匹配,为了模糊获取所有的triggerKey或者jobKey
GroupMatcher groupMatcher = GroupMatcher.groupEquals(groupName);
//获取所有的triggerKey
Set<TriggerKey> triggerKeySet = scheduler.getTriggerKeys(groupMatcher);
for (TriggerKey triggerKey : triggerKeySet) {
//通过triggerKey在scheduler中获取trigger对象
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
//获取trigger拥有的Job
JobKey jobKey = trigger.getJobKey();
JobDetailImpl jobDetail = (JobDetailImpl) scheduler.getJobDetail(jobKey);
//组装需要显示的数据
Map<String, String> jobMap = new HashMap<>();
//分组名称
jobMap.put("groupName", groupName);
//定时任务名称
jobMap.put("jobDetailName", jobDetail.getName());
//cron表达式
String cronExpression = trigger.getCronExpression();
jobMap.put("jobCronExpression", cronExpression);
//时区
jobMap.put("timeZone", trigger.getTimeZone().getID());
//下次运行时间
CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
cronTriggerImpl.setCronExpression(cronExpression);
List<Date> dates = TriggerUtils.computeFireTimes(cronTriggerImpl, null, 20);
jobMap.put("nextRunDateTime", DateUtil.format(dates.get(0), "yyyy-MM-dd HH:mm:ss"));
jobList.add(jobMap);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return jobList;
}
}
3 调试结果
![](https://img-blog.csdnimg.cn/20210615200332224.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4OTc0NjM4,size_16,color_FFFFFF,t_70)