关于quartz对定时任务的管理
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于quartz对定时任务的管理相关的知识,希望对你有一定的参考价值。
请问有谁知道Quartz有没有Web页面的管理应用,可以灵活控制定时任务的起停和执行周期,官方的最好,多谢!
我曾经在其他网站上看到那些管理定时任务的页面,而且好像不是个人用的页面,简直和企业应用差不多……
我已经找了2天了,丝毫没有头绪,也不知道官方网站是不是http://www.opensymphony.com/quartz/
而且论坛都看过了,朋友也问了,就是找不到……
请您指点,谢谢
到官网下载帮助。
Quartz+Spring Boot实现动态管理定时任务
项目实践过程中碰到一个动态管理定时任务的需求:针对每个人员进行信息的定时更新,具体更新时间可随时调整、启动、暂定等。
思路
将每个人员信息的定时配置保存到数据库中,这样实现了任务的动态展示和管理。任务的每一次新增或变更,都会去数据库变更信息。
设置一个统一的任务管理器,专门负责动态任务的增删改查。
POM依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>dynamic-quartz</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>dynamic-quartz</name>
<description>动态定时任务管理</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- jdbc driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/wujiwen
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
profiles:
active: dev
logback-spring.xml
<configuration>
<jmxConfigurator />
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
</appender>
<logger name="org.springframework">
<level value="ERROR" />
</logger>
<logger name="org.mybatis">
<level value="ERROR" />
</logger>
<logger name="java.sql.Connection">
<level value="DEBUG" />
</logger>
<logger name="java.sql.Statement">
<level value="DEBUG" />
</logger>
<logger name="java.sql.PreparedStatement">
<level value="DEBUG" />
</logger>
<logger name="java.sql.ResultSet">
<level value="DEBUG"/>
</logger>
<logger name="org.apache.http">
<level value="INFO" />
</logger>
<logger name="org.quartz">
<level value="INFO" />
</logger>
<springProfile name="dev,test">
<root>
<level value="DEBUG" />
<appender-ref ref="stdout" />
</root>
</springProfile>
</configuration>
CronEntity.java
保存在数据库中的表达式管理器.
package com.example.dynamicquartz.bean;
import java.io.Serializable;
import java.util.Date;
/**
* created with IntelliJ IDEA.
* packageName : com.example.dynamicquartz.bean
* author : wujw
* date : 2018/9/9 16:23
* version : 1.0.0
* description : TODO
*/
public class CronEntity implements Serializable {
private static final long serialVersionUID = -3406421161273529348L;
private String id;
private String userId; //用户标识
private String cron; //表达式
private String quarzName; //任务名称
private String schedulerClass;//定时任务类
private Date time;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
}
public String getQuarzName() {
return quarzName;
}
public void setQuarzName(String quarzName) {
this.quarzName = quarzName;
}
public String getSchedulerClass() {
return schedulerClass;
}
public void setSchedulerClass(String schedulerClass) {
this.schedulerClass = schedulerClass;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@Override
public String toString() {
return "CronEntity{" +
"id=‘" + id + ‘‘‘ +
", userId=‘" + userId + ‘‘‘ +
", cron=‘" + cron + ‘‘‘ +
", quarzName=‘" + quarzName + ‘‘‘ +
", schedulerClass=‘" + schedulerClass + ‘‘‘ +
", time=" + time +
‘}‘;
}
}
CronMapper
package com.example.dynamicquartz.dao;
import com.example.dynamicquartz.bean.CronEntity;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* created with IntelliJ IDEA.
* packageName : com.example.dynamicquartz
* author : wujw
* date : 2018/9/9 20:14
* version : 1.0.0
* description : TODO
*/
@Mapper
public interface CronMapper{
@Select("select * from cron_table where id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "userId", column = "user_id"),
@Result(property = "cron", column = "cron"),
@Result(property = "quarzName", column = "quarz_name"),
@Result(property = "schedulerClass", column = "scheduler_class"),
@Result(property = "time", column = "time")
})
CronEntity load(String id);
@Insert("insert into cron_table(id,userId,cron,quartzName,schedulerClass,time)" +
"values(#{id},#{user_id},#{cron},#{quartz_name},#{scheduler_class},# {time})")
void insert(CronEntity cronEntity);
@Select("select * from cron_table")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "userId", column = "user_id"),
@Result(property = "cron", column = "cron"),
@Result(property = "quarzName", column = "quarz_name"),
@Result(property = "schedulerClass", column = "scheduler_class"),
@Result(property = "time", column = "time")
})
List<CronEntity> queryAll();
@Update("update cron_table set cron=#{1} where id =#{0}")
void updateCron(String id,String cron);
}
ICronService
package com.example.dynamicquartz.serivce;
import com.example.dynamicquartz.bean.CronEntity;
import java.util.List;
/**
* created with IntelliJ IDEA.
* packageName : com.example.dynamicquartz
* author : wujw
* date : 2018/9/9 19:54
* version : 1.0.0
* description : TODO
*/
public interface ICronService{
void sendEmail(String quartzName);
void sendSms(String quartzName);
CronEntity findByCronId(String id );
void update(CronEntity cronEntity);
List<CronEntity> findAll();
}
CronServiceImpl
package com.example.dynamicquartz.serivce;
import com.example.dynamicquartz.bean.CronEntity;
import com.example.dynamicquartz.dao.CronMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* created with IntelliJ IDEA.
* packageName : com.example.dynamicquartz.serivce
* author : wujw
* date : 2018/9/9 19:55
* version : 1.0.0
* description : TODO
*/
@Service
public class CronServiceImpl implements ICronService{
@Autowired
private CronMapper cronMapper;
@Override
public void sendEmail(String quartzName) {
System.out.println(quartzName +" 正在发送邮件");
}
@Override
public void sendSms(String quartzName) {
System.out.println(quartzName +"正在发送短信");
}
@Override
public CronEntity findByCronId(String id) {
return this.cronMapper.load(id);
}
@Override
public void update(CronEntity cronEntity) {
this.cronMapper.insert(cronEntity);
}
@Override
public List<CronEntity> findAll() {
return this.cronMapper.queryAll();
}
}
QuartzManager
package com.example.dynamicquartz.serivce;
import com.example.dynamicquartz.bean.CronEntity;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import java.util.Date;
/**
* created with IntelliJ IDEA.
* packageName : com.example.dynamicquartz
* author : wujw
* date : 2018/9/9 19:31
* version : 1.0.0
* description : TODO
*/
@Configuration
public class QuartzManager {
@Autowired
private Scheduler scheduler;
@Autowired
private ICronService iCronService;
public void start(String id) throws SchedulerException {
CronEntity cronEntity = iCronService.findByCronId(id);
if(cronEntity!= null){
startJob(scheduler,cronEntity.getQuarzName(),cronEntity.getCron(),cronEntity.getSchedulerClass());
}
}
private void startJob(Scheduler scheduler,String name,String cron,String className) throws SchedulerException {
// 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
// JobDetail 是具体Job实例
Class<Job> jobClass = null;
try {
//实例化具体的Job任务
jobClass = (Class<Job>) Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, "group1").build();
// 基于表达式构建触发器
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
// CronTrigger表达式触发器 继承于Trigger
// TriggerBuilder 用于构建触发器实例
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(name, "group1")
.withSchedule(cronScheduleBuilder).build();
scheduler.scheduleJob(jobDetail, cronTrigger);
}
/**
* 获取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);
}
}
创建两个Task类,分别执行不同的任务
public class EmailTask implements Job {
private Logger logger = LoggerFactory.getLogger(EmailTask.class);
@Autowired
private ICronService iCronService;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
logger.info("EmailTask task start execute.");
//模拟任务执行
iCronService.sendEmail(jobExecutionContext.getJobDetail().getKey().getName());
}
}
public class SmsTask implements Job {
private Logger logger = LoggerFactory.getLogger(SmsTask.class);
@Autowired
private ICronService iCronService;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
logger.info("SmsTask task start execute.");
//模拟任务执行
iCronService.sendSms(jobExecutionContext.getJobDetail().getKey().getName());
}
}
SchedulerController
@RestController
@RequestMapping("/scheduler")
public class SchedulerController{
@Autowired
QuartzManager quartzManager;
@RequestMapping(value = "/start", method = RequestMethod.GET)
@ResponseBody
public String start(@RequestParam(name = "id", defaultValue = "") String id) {
try {
quartzManager.start(id);
} catch (SchedulerException e) {
e.printStackTrace();
}
return "启动成功";
}
}
cron_table.sql
CREATE TABLE `cron_table` (
`id` varchar(11) collate utf8_bin NOT NULL,
`user_id` varchar(11) collate utf8_bin default NULL,
`cron` varchar(255) collate utf8_bin default NULL,
`quarz_name` varchar(255) collate utf8_bin default NULL,
`scheduler_class` varchar(255) collate utf8_bin default NULL,
`time` datetime default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Records of cron_table
-- ----------------------------
INSERT INTO `cron_table` VALUES (‘1‘, ‘AAA‘, ‘0/5 * * * * ?‘, ‘用户AAA‘, ‘com.example.dynamicquartz.job.SmsTask‘, ‘2018-09-06 20:26:55‘);
INSERT INTO `cron_table` VALUES (‘2‘, ‘BBB‘, ‘0/2 * * * * ?‘, ‘用户BBB‘, ‘com.example.dynamicquartz.job.EmailTask‘, ‘2018-09-09 21:02:08‘);
测试结果
http://localhost:8080/scheduler/start?id=1
http://localhost:8080/scheduler/start?id=2
2018-09-09 21:05:08,386 [http-nio-8080-exec-2] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Preparing: select * from cron_table where id = ?
2018-09-09 21:05:08,408 [http-nio-8080-exec-2] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Parameters: 1(String)
2018-09-09 21:05:08,427 [http-nio-8080-exec-2] DEBUG com.example.dynamicquartz.dao.CronMapper.load - <== Total: 1
2018-09-09 21:05:10,036 [quartzScheduler_Worker-1] INFO com.example.dynamicquartz.job.SmsTask - SmsTask task start execute.
用户AAA正在发送短信
2018-09-09 21:05:11,581 [http-nio-8080-exec-1] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Preparing: select * from cron_table where id = ?
2018-09-09 21:05:11,582 [http-nio-8080-exec-1] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Parameters: 2(String)
2018-09-09 21:05:11,584 [http-nio-8080-exec-1] DEBUG com.example.dynamicquartz.dao.CronMapper.load - <== Total: 1
2018-09-09 21:05:12,013 [quartzScheduler_Worker-2] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用户BBB 正在发送邮件
2018-09-09 21:05:14,002 [quartzScheduler_Worker-3] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用户BBB 正在发送邮件
2018-09-09 21:05:15,001 [quartzScheduler_Worker-4] INFO com.example.dynamicquartz.job.SmsTask - SmsTask task start execute.
用户AAA正在发送短信
2018-09-09 21:05:16,001 [quartzScheduler_Worker-5] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用户BBB 正在发送邮件
2018-09-09 21:05:18,001 [quartzScheduler_Worker-6] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用户BBB 正在发送邮件
2018-09-09 21:05:20,000 [quartzScheduler_Worker-7] INFO com.example.dynamicquartz.job.SmsTask - SmsTask task start execute.
用户AAA正在发送短信
2018-09-09 21:05:20,001 [quartzScheduler_Worker-8] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用户BBB 正在发送邮件
2018-09-09 21:05:22,001 [quartzScheduler_Worker-9] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用户BBB 正在发送邮件
2018-09-09 21:05:24,000 [quartzScheduler_Worker-10] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用户BBB 正在发送邮件
2018-09-09 21:05:25,001 [quartzScheduler_Worker-1] INFO com.example.dynamicquartz.job.SmsTask - SmsTask task start execute.
用户AAA正在发送短信
2018-09-09 21:05:26,000 [quartzScheduler_Worker-2] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
用户BBB 正在发送邮件
2018-09-09 21:05:28,001 [quartzScheduler_Worker-3] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
可以看出,AAA的间隔时间时5s,BBB的间隔时间时2s.
到这里我们的测试已经一本完成了,接下来就是针对任务的更新,停止和启动了,只需要调用QuartzManager
对应的方法即可,必要时更新一下数据库就好啦。
以上是关于关于quartz对定时任务的管理的主要内容,如果未能解决你的问题,请参考以下文章