SpringBoot整合quartz实现动态启动,停止定时任务功能
注意:这个方法当程序重启之后会失效,所以必须将定时任务持久化到数据库,然后程序启动的时候重新把数据库的定时任务加载到quartz中
springboot程序启动初始化代码参考:https://www.cnblogs.com/pxblog/p/14995261.html
引入maven
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
TaskJob.java 任务执行类
package com.test.cms.task; import com.test.cms.service.TaskService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import java.util.Date; /**
* @PersistJobDataAfterExecution 和 @DisallowConcurrentExecution
* 表示不让某个定时任务并发执行保证上一个任务执行完后,再去执行下一个任务
*/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Component
public class TaskJob implements Job { /**
* 可以直接注入service层。这里只是演示,没有这个类
*/
@Autowired
private TaskService taskService; @Override
public void execute(JobExecutionContext context) {
JobDataMap jobDataMap=context.getJobDetail().getJobDataMap();
System.out.println("11"+new Date()+" "+jobDataMap.getString("value")+" "+context.getJobDetail().getKey());
} }
控制器
TaskController.java
package com.test.cms.controller; import com.test.cms.task.TaskJob;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.*; @RestController
public class TaskController { /**
* 启动任务 需要自己完善逻辑,这里我用uuid作为taskCode 保证唯一
* 启动之前要通过数据库查询是否任务已经启动,如果启动了就不能启动了
* 启动成功了 要把数据库的任务状态改为启动中
*/
@RequestMapping(value = "/task/start")
public void start() {
String uuid = UUID.randomUUID().toString();
System.out.println(uuid);
startTask(uuid); } /**
* 停止任务 需要自己完善逻辑
* @param taskCode 传入启动任务时设置的taskCode参数
*/
@RequestMapping(value = "/task/stop")
public void stop(String taskCode) {
endTask(taskCode);
} /**
* 开始任务调度
*
* @param taskCode 任务名称 需要唯一标识,停止任务时需要用到
*/
private void startTask(String taskCode){
//任务开始的corn表达式
String cronExpress = "*/5 * * * * ?";
if (cronExpress.indexOf("null") == -1) {
try {
JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
jobDetailFactoryBean.setName(taskCode);
jobDetailFactoryBean.setGroup(Scheduler.DEFAULT_GROUP);
//TaskJob.class 是任务所要执行操作的类
jobDetailFactoryBean.setJobClass(TaskJob.class);
//任务需要的参数可以通过map方法传递,
Map map = new HashMap();
map.put("value", "我在传递参数");
jobDetailFactoryBean.setJobDataMap(getJobDataMap(map));
jobDetailFactoryBean.afterPropertiesSet();
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setBeanName(taskCode);
cronTriggerFactoryBean.setCronExpression(cronExpress);
cronTriggerFactoryBean.setGroup(Scheduler.DEFAULT_GROUP);
cronTriggerFactoryBean.setName("cron_" + taskCode);
cronTriggerFactoryBean.afterPropertiesSet();
scheduler.scheduleJob(jobDetailFactoryBean.getObject(), cronTriggerFactoryBean.getObject());
System.out.println(taskCode+"任务启动成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println(taskCode+"任务启动失败");
}
}
} /**
* 结束任务调度
*
* @param taskCode
*/
private void endTask(String taskCode) {
try {
scheduler.deleteJob(JobKey.jobKey(taskCode, Scheduler.DEFAULT_GROUP));
System.out.println(taskCode+"任务停止成功");
} catch (SchedulerException e) {
e.printStackTrace();
System.out.println(taskCode+"任务停止失败");
}
} /**
* 将HashMap转为JobDataMap
* @param params
* @return
*/
private JobDataMap getJobDataMap(Map<String, String> params) {
JobDataMap jdm = new JobDataMap();
Set<String> keySet = params.keySet();
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
String key = it.next();
jdm.put(key, params.get(key));
}
return jdm;
} @Autowired
private Scheduler scheduler;
}
启动类要加上注解@EnableScheduling
package com.test.cms; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication
@EnableScheduling //要加上开启定时任务的注解
public class CmsApplication { public static void main(String[] args) {
SpringApplication.run(CmsApplication.class, args);
} }
JAVA日期Date格式转corn表达式:https://www.cnblogs.com/pxblog/p/14992923.html
SpringBoot整合quartz实现动态启动,停止定时任务功能的更多相关文章
- springboot整合Quartz实现动态配置定时任务
前言 在我们日常的开发中,很多时候,定时任务都不是写死的,而是写到数据库中,从而实现定时任务的动态配置,下面就通过一个简单的示例,来实现这个功能. 一.新建一个springboot工程,并添加依赖 & ...
- SpringBoot整合Quartz定时任务 系统job Spring Boot教程 调度任务
原文地址:https://www.cnblogs.com/allalongx/p/8477368.html 构建工程 创建一个Springboot工程,在它的程序入口加上@EnableScheduli ...
- SpringBoot整合Quartz定时任务
记录一个SpringBoot 整合 Quartz 的Demo实例 POM.XML文件 <!-- 定时器任务 quartz需要导入的坐标 --> <dependency> < ...
- 项目ITP(六) spring4.0 整合 Quartz 实现动态任务调度
前言 系列文章:[传送门] 项目需求: http://www.cnblogs.com/Alandre/p/3733249.html 上一博客写的是基本调度,后来这只能用于,像每天定个时间 进行数据库备 ...
- SpringBoot整合MyBatisPlus配置动态数据源
目录 SpringBoot整合MyBatisPlus配置动态数据源 SpringBoot整合MyBatisPlus配置动态数据源 推文:2018开源中国最受欢迎的中国软件MyBatis-Plus My ...
- SpringBoot整合Quartz及log4j实例
SpringBoot整合Quartz及log4j实例 因为之前项目中经常会做一些定时Job的东西,所以在此记录一下,目前项目中已经使用elastic-job,这个能相对比Quartz更加简单方便一些, ...
- Spring 整合 Quartz 实现动态定时任务
复制自:https://www.2cto.com/kf/201605/504659.html 最近项目中需要用到定时任务的功能,虽然Spring 也自带了一个轻量级的定时任务实现,但感觉不够灵活,功能 ...
- 【转】Spring 整合 Quartz 实现动态定时任务
http://blog.csdn.net/u014723529/article/details/51291289 最近项目中需要用到定时任务的功能,虽然spring 也自带了一个轻量级的定时任务实现, ...
- Spring 整合 Quartz 实现动态定时任务(附demo)
最近项目中需要用到定时任务的功能,虽然Spring 也自带了一个轻量级的定时任务实现,但感觉不够灵活,功能也不够强大.在考虑之后,决定整合更为专业的Quartz来实现定时任务功能. 普通定时任务 首先 ...
随机推荐
- NextDenovo 组装基因组
NextDenovo 是有武汉未来组团队开发出来用于组装ONT,Pacbio, HIFI (默认参数可对60-100X数据更有效),可通过correct--assemble对其进行组装.组装后,每个碱 ...
- pycharm两个交互模式
- centos安装后的个人工具
1.安装vim工具 yum -y install vim 安装完成后在家目录下新建一个.vimrc的配置文件.辅助vim软件功能. set number " 显示行号 set cursorl ...
- 在前端页面中使用Markdown并且优化a标签
近期在自己的项目中加入了对 Markdown 语法 的支持,主要用到的是markedjs这个项目.该项目托管在github上,地址为:https://github.com/markedjs/marke ...
- DOM给表格添加新一行和删除整个行的内容
DOM用appendChild()给表格添加新一行时,要注意,在HTML中没特别设置<thead>,<tbody>时,会自动添加上,所以要选择表格第一个元素在添加tr. // ...
- 中小型企业SaaS行业将崛起于新十年
2020开始的新十年,国内中小型企业SaaS市场将迎来蓬勃生机,四大助推器已经就绪 第一,云服务打好底座: 随着阿里云.腾讯云乃至华为云的蓬勃发展,基础设施的不断完善,为中小型Saas企业的发展,提供 ...
- linux 内存变量的分布
我们知道,linux通过虚拟内存管理进程的内存(进程的地址空间),而进程的地址空间分布如下 : 从进程的空间中可以看出,内存中的变量有的来自可执行elf文件,在elf文件中已经分配好存储空间,有的是在 ...
- web必知,多终端适配
导读 移动端适配,是我们在开发中经常会遇到的,这里面可能会遇到非常多的问题: 1px问题 UI图完美适配方案 iPhoneX适配方案 横屏适配 高清屏图片模糊问题 ... 上面这些问题可能我们在开发中 ...
- Https原理及证书管理
Https原理及证书管理 SSL(Secure Sockets Layer,安全套接层)/TLS(Transport Layer Security,传输层安全)保证了客户端web服务器的连接安全.客户 ...
- c++string转const char*与char*
#include <iostream> #include <string> #include <memory> using namespace std; const ...