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来实现定时任务功能. 普通定时任务 首先 ...
随机推荐
- tabix 操作VCF文件
tabix 可以对NGS分析中常见格式的文件建立索引,从而加快访问速度,不仅支持VCF文件,还支持BED, GFF,SAM等格式. 下载地址: 1 https://sourceforge.net/pr ...
- miRNA预测工具miRDeep-P2
之前讲过预测植物miRNA的一款软件miR-PREFER, 今天在介绍一款软件miRDeep-p2, 也叫miRDP2 安装 在此之前,应安装一下软件 Bowite, Bowtie2, Vienna ...
- linux 线程函数小结
由于主线程已经开始跑了,次线程还在使用串口打印需要一点时间,因此打印的都是重复的. #include "pthread.h" #include "stdio.h" ...
- 巩固java第六天
巩固内容: HTML 空元素 没有内容的 HTML 元素被称为空元素.空元素是在开始标签中关闭的. <br> 就是没有关闭标签的空元素(<br> 标签定义换行). 在 XHTM ...
- navicate连接Mysql5.7时,显示Access denied for user 'root'@'localhost' (using password: YES) 错误
最近新装了Mysql5.7,按如下设置好了允许远程连接 (1)找到mysql配置文件并修改 sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf 将bind-ad ...
- 顺序栈(C++)
栈的定义为只允许在表的末端进行插入和删除的线性表.简而言之就是先进后出的线性表. 插入和删除的一端被称呼为栈顶(top),而不允许插入删除的一端被称为栈底(bottom).无元素时的栈即为空栈. 使用 ...
- Linux常用命令之文件权限管理
Linux文件权限管理1.改变文件或目录的权限:chmod命令详解命令名称:chmod命令所在路径:/bin/chmod执行权限:所有用户语法:chmod [{ugoa}{+-=}{rwx}] [文件 ...
- fastJson序列化
在pojo实体中有map<String,Object>的属性,有个key是user它存储在数据库中是用户的id数组,而在aop里会对这个属性做用户详细信息查询并重新put给user.在做J ...
- Dubbo服务暴露延迟
Dubbo 2.6.5 版本以后,如果我们的服务启动过程需要warmup事件,就可以使用delay进行服务延迟暴露.只需在服务提供者的<dubbo:service/>标签中添加delay属 ...
- 【编程思想】【设计模式】【结构模式Structural】享元模式flyweight
Python版 https://github.com/faif/python-patterns/blob/master/structural/flyweight.py #!/usr/bin/env p ...