注意:这个方法当程序重启之后会失效,所以必须将定时任务持久化到数据库,然后程序启动的时候重新把数据库的定时任务加载到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实现动态启动,停止定时任务功能的更多相关文章

  1. springboot整合Quartz实现动态配置定时任务

    前言 在我们日常的开发中,很多时候,定时任务都不是写死的,而是写到数据库中,从而实现定时任务的动态配置,下面就通过一个简单的示例,来实现这个功能. 一.新建一个springboot工程,并添加依赖 & ...

  2. SpringBoot整合Quartz定时任务 系统job Spring Boot教程 调度任务

    原文地址:https://www.cnblogs.com/allalongx/p/8477368.html 构建工程 创建一个Springboot工程,在它的程序入口加上@EnableScheduli ...

  3. SpringBoot整合Quartz定时任务

    记录一个SpringBoot 整合 Quartz 的Demo实例 POM.XML文件 <!-- 定时器任务 quartz需要导入的坐标 --> <dependency> < ...

  4. 项目ITP(六) spring4.0 整合 Quartz 实现动态任务调度

    前言 系列文章:[传送门] 项目需求: http://www.cnblogs.com/Alandre/p/3733249.html 上一博客写的是基本调度,后来这只能用于,像每天定个时间 进行数据库备 ...

  5. SpringBoot整合MyBatisPlus配置动态数据源

    目录 SpringBoot整合MyBatisPlus配置动态数据源 SpringBoot整合MyBatisPlus配置动态数据源 推文:2018开源中国最受欢迎的中国软件MyBatis-Plus My ...

  6. SpringBoot整合Quartz及log4j实例

    SpringBoot整合Quartz及log4j实例 因为之前项目中经常会做一些定时Job的东西,所以在此记录一下,目前项目中已经使用elastic-job,这个能相对比Quartz更加简单方便一些, ...

  7. Spring 整合 Quartz 实现动态定时任务

    复制自:https://www.2cto.com/kf/201605/504659.html 最近项目中需要用到定时任务的功能,虽然Spring 也自带了一个轻量级的定时任务实现,但感觉不够灵活,功能 ...

  8. 【转】Spring 整合 Quartz 实现动态定时任务

    http://blog.csdn.net/u014723529/article/details/51291289 最近项目中需要用到定时任务的功能,虽然spring 也自带了一个轻量级的定时任务实现, ...

  9. Spring 整合 Quartz 实现动态定时任务(附demo)

    最近项目中需要用到定时任务的功能,虽然Spring 也自带了一个轻量级的定时任务实现,但感觉不够灵活,功能也不够强大.在考虑之后,决定整合更为专业的Quartz来实现定时任务功能. 普通定时任务 首先 ...

随机推荐

  1. SAM 感性瞎扯

    SAM 做题笔记. 这里是 SAM 感性瞎扯. 最近学了后缀自动机(Suffix_Automaton,SAM),深感其巧妙之处,故写文以记之. 部分文字与图片来源于 OI-Wiki,hihoCoder ...

  2. Eigensoft-smartpca分析PCA报错:warning (mapfile): bad chrom: Segmentation fault

    目录 问题 解决 问题 一直以来用Eigensoft的smartpca来做群体遗传的PCA分析很顺畅,结果也比较靠谱. 但今天报错如下: $ ~/miniconda3/bin/smartpca -p ...

  3. 1D RKDG to shallow water equations

    RKDG to shallow water equations 1.Governing Equations \[\frac{\partial U}{\partial t} + \frac{\parti ...

  4. [R] cbind和filter函数的坑

    最近我用cbind函数整合数据后,再用filter过滤数据,碰到了一个大坑. 以两组独立样本t检验筛选差异蛋白为例进行说明吧. pro2 <- df2[1:6] Pvalue<-c(rep ...

  5. R语言与医学统计图形-【15】ggplot2几何对象之线图

    ggplot2绘图系统--几何对象之线图 曲线:点连线.路径曲线.时间序列曲线.模型拟合曲线...... 直线:水平直线.垂直直线.斜线. 1.曲线 对象及其参数. #路径图 geom_path(ma ...

  6. 《Redis设计与实现》知识点目录

    Redis设计与实现 第一部分 数据结构与对象 第二章 简单动态字符串 p8 简单动态字符串SDS 2.1 SDS的定义 p9 每个sds.h/sdshdr结构表示一个SDS值 2.2 SDS与C字符 ...

  7. 基于Kubernetes实现前后端应用的金丝雀发布

    基于Kubernetes实现前后端应用的金丝雀发布 公司的研发管理平台实现了Gitlab+Kubernetes的Devops,在ToB和ToC场景中,由于用户量大,且预发布环境和生产环境或多或少存在差 ...

  8. nodejs-Cluster模块

    JavaScript 标准参考教程(alpha) 草稿二:Node.js Cluster模块 GitHub TOP Cluster模块 来自<JavaScript 标准参考教程(alpha)&g ...

  9. 用UIScrollview做一个网易scrollviewbar

    效果如上,点击出现的图片是用UIImageview添加上的,比较简陋 我用了两种方法,第一种是直接在viewcontroller里面写代码 第二种是用了一个类来封装这个scrollviewbar 对外 ...

  10. 【Python】【Basic】MacOS上搭建Python开发环境

    1. Python3 1.1. 下载地址:https://www.python.org/downloads/mac-osx/ 1.1.1. PKG包安装: 没啥可说的,点点点,下一步而已,不用手动配置 ...