1. 首先, 还是喜闻乐见的导包

 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

2. 处理schedule工具

 package com.hoolink.schedule.util;

 import com.hoolink.sdk.bo.device.ScreenPlayScheduleBO;
import com.hoolink.sdk.utils.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.*; import java.time.LocalDate;
import java.util.List; /**
* @author <a herf="mailto:yanwu0527@163.com">XuBaofeng</a>
* @date 2019-05-31 17:29.
* <p>
* description:
* DisallowConcurrentExecution: 不允许并发执行
*/
@Slf4j
@DisallowConcurrentExecution
public class ScreenPlayUtil { /**
* 批量创建定时任务
*
* @param scheduler
* @param screens
*/
public static void createAll(Scheduler scheduler, List<ScreenPlayScheduleBO> screens) {
if (CollectionUtils.isEmpty(screens)) {
return;
}
screens.forEach(screen -> {
createJob(scheduler, screen);
});
} /**
* 添加一个定时任务
*
* @param scheduler 调度器
* @param screen 任务
*/
public static void createJob(Scheduler scheduler, ScreenPlayScheduleBO screen) {
try {
log.info("create job, time: {}, screen: {}", LocalDate.now(), screen);
Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(screen.getClassName());
JobDataMap jobDataMap = new JobDataMap(JSONUtils.stringToMap(JSONUtils.toJSONString(screen)));
// 任务名,任务组,任务执行类
JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(screen.getJobName(), screen.getJobGroup())
.withDescription("定时任务").setJobData(jobDataMap).build();
// 触发器名,触发器组
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(screen.getCronExpression())
.withMisfireHandlingInstructionDoNothing();
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(screen.getTriggerName(), screen.getTriggerGroup())
.withDescription(screen.getDescription()).withSchedule(scheduleBuilder).startNow().build();
// 触发器时间设定
scheduler.scheduleJob(jobDetail, trigger);
// 启动
if (!scheduler.isShutdown()) {
startJobs(scheduler);
}
} catch (Exception e) {
log.error("create schedule job error", e);
}
} /**
* 批量更新定时任务
*
* @param scheduler
* @param screens
*/
public static void updateAll(Scheduler scheduler, List<ScreenPlayScheduleBO> screens) {
if (CollectionUtils.isEmpty(screens)) {
return;
}
screens.forEach(screen -> {
updateJob(scheduler, screen);
});
} /**
* 修改一个任务的触发时间
*
* @param scheduler
* @param screen
*/
public static void updateJob(Scheduler scheduler, ScreenPlayScheduleBO screen) {
try {
log.info("update job, time: {}, screen:{}", LocalDate.now(), screen);
TriggerKey triggerKey = new TriggerKey(screen.getTriggerName(), screen.getTriggerGroup());
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
if (trigger == null) {
createJob(scheduler, screen);
return;
}
String cron = trigger.getCronExpression();
if (!cron.equalsIgnoreCase(screen.getCronExpression())) {
removeJob(scheduler, screen);
createJob(scheduler, screen);
}
} catch (Exception e) {
log.error("update schedule job error", e);
}
} /**
* 清除所有的定时任务
*
* @param scheduler
*/
public static void removeAll(Scheduler scheduler) {
try {
log.info("remove all schedule job, time: {}", LocalDate.now());
scheduler.clear();
} catch (Exception e) {
log.error("remove all schedule job error.", e);
}
} /**
* 批量清除指定的定时任务
*
* @param scheduler
*/
public static void removeAll(Scheduler scheduler, List<ScreenPlayScheduleBO> screens) {
if (CollectionUtils.isEmpty(screens)) {
return;
}
screens.forEach(screen -> {
removeJob(scheduler, screen);
});
} /**
* 移除一个任务
*
* @param scheduler
* @param screen
*/
public static void removeJob(Scheduler scheduler, ScreenPlayScheduleBO screen) {
try {
log.info("remove job, time: {}, screen:{}", LocalDate.now(), screen);
JobKey jobKey = new JobKey(screen.getJobName(), screen.getJobGroup());
TriggerKey triggerKey = new TriggerKey(screen.getTriggerName(), screen.getTriggerGroup());
// 停止触发器
scheduler.pauseTrigger(triggerKey);
// 移除触发器
scheduler.unscheduleJob(triggerKey);
// 删除任务
scheduler.deleteJob(jobKey);
} catch (Exception e) {
log.error("remove schedule job error", e);
}
} /**
* 启动所有定时任务
*
* @param scheduler 调度器
*/
public static void startJobs(Scheduler scheduler) {
try {
log.info("start schedule job, time: {}", LocalDate.now());
scheduler.start();
} catch (Exception e) {
log.error("start schedule job error", e);
}
} /**
* 关闭所有定时任务
*
* @param scheduler 调度器
*/
public static void shutdownJobs(Scheduler scheduler) {
try {
log.info("shutdown schedule job, time: {}", LocalDate.now());
if (!scheduler.isShutdown()) {
scheduler.shutdown();
}
} catch (Exception e) {
log.error("shutdown schedule job error", e);
}
} }

3. BO

 package com.hoolink.sdk.bo.device;

 import lombok.Data;

 import java.io.Serializable;

 /**
* @author <a herf="mailto:yanwu0527@163.com">XuBaofeng</a>
* @date 2019-05-31 17:31.
* <p>
* description:
*/
@Data
public class ScreenPlayScheduleBO implements Serializable {
private static final long serialVersionUID = 4226193119686522141L; private Long configId; /*** 执行任务的类名称 */
private String className; /*** 定时任务表达式 */
private String cronExpression; /*** 任务名称 */
private String jobName; /*** 任务分组 */
private String jobGroup; /*** 触发器名称 */
private String triggerName; /*** 触发器分组 */
private String triggerGroup; /*** 任务描述 */
private String description; /*** 创建时间 */
private Long createTime; /*** 定时任务任务ID */
private Long playId; /*** 开启\关闭(0:关闭;1:开启) */
private Boolean playStatus;
}

5. 处理定时任务

 package com.hoolink.schedule.job;

 import com.hoolink.schedule.consumer.ScreenClient;
import com.hoolink.sdk.bo.device.ScreenPlayScheduleBO;
import com.hoolink.sdk.utils.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.servicecomb.foundation.common.utils.BeanUtils;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException; import java.time.LocalDateTime; /**
* @author <a herf="mailto:yanwu0527@163.com">XuBaofeng</a>
* @date 2019-05-31 17:29.
* <p>
* description:
* DisallowConcurrentExecution: 不允许并发执行
*/
@Slf4j
@DisallowConcurrentExecution
public class ScreenPlayJob implements Job { @Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap jobDataMap = context.getMergedJobDataMap();
ScreenPlayScheduleBO mediaTaskBO = JSONUtils.parse(JSONUtils.toJSONString(jobDataMap), ScreenPlayScheduleBO.class);
log.info("screen play control job start, time: {} param: {}", LocalDateTime.now(), mediaTaskBO);
ScreenClient screenClient = BeanUtils.getContext().getBean(ScreenClient.class);
screenClient.playControl(mediaTaskBO);
} }

6. 调用schedule工具

 package com.hoolink.schedule.controller;

 import com.hoolink.schedule.util.ScreenPlayUtil;
import com.hoolink.sdk.annotation.LogAndParam;
import com.hoolink.sdk.bo.BackBO;
import com.hoolink.sdk.bo.device.ScreenPlayScheduleBO;
import com.hoolink.sdk.utils.BackBOUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.List; /**
* @author <a herf="mailto:yanwu0527@163.com">XuBaofeng</a>
* @date 2019-06-01 14:59.
* <p>
* description:
*/
@RestController
@RequestMapping("/screen/play/")
@RestSchema(schemaId = "screenPlayController")
public class ScreenPlayController {
@Autowired
private Scheduler scheduler; @PostMapping(value = "create")
@ApiOperation(value = "创建定时任务")
@LogAndParam(value = "创建定时任务失败")
public BackBO<Void> create(@RequestBody ScreenPlayScheduleBO screen) {
ScreenPlayUtil.createJob(scheduler, screen);
return BackBOUtil.defaultBackBO();
} @PostMapping(value = "createAll")
@ApiOperation(value = "批量创建定时任务")
@LogAndParam(value = "批量定时任务失败")
public BackBO<Void> createAll(@RequestBody List<ScreenPlayScheduleBO> screens) {
ScreenPlayUtil.createAll(scheduler, screens);
return BackBOUtil.defaultBackBO();
} @PostMapping(value = "update")
@ApiOperation(value = "更新定时任务")
@LogAndParam(value = "更新定时任务失败")
public BackBO<Void> update(@RequestBody ScreenPlayScheduleBO screen) {
ScreenPlayUtil.updateJob(scheduler, screen);
return BackBOUtil.defaultBackBO();
} @PostMapping(value = "updateAll")
@ApiOperation(value = "更新定时任务")
@LogAndParam(value = "更新定时任务失败")
public BackBO<Void> updateAll(@RequestBody List<ScreenPlayScheduleBO> screens) {
ScreenPlayUtil.updateAll(scheduler, screens);
return BackBOUtil.defaultBackBO();
} @PostMapping(value = "remove")
@ApiOperation(value = "删除定时任务")
@LogAndParam(value = "删除定时任务失败")
public BackBO<Void> remove(@RequestBody ScreenPlayScheduleBO screen) {
ScreenPlayUtil.removeJob(scheduler, screen);
return BackBOUtil.defaultBackBO();
} @PostMapping(value = "deleteAll")
@ApiOperation(value = "清除所有的定时任务")
@LogAndParam(value = "清除所有的定时任务失败")
public BackBO<Void> deleteAll() {
ScreenPlayUtil.removeAll(scheduler);
return BackBOUtil.defaultBackBO();
} @PostMapping(value = "removeAll")
@ApiOperation(value = "清除所有的定时任务")
@LogAndParam(value = "清除所有的定时任务失败")
public BackBO<Void> removeAll(@RequestBody List<ScreenPlayScheduleBO> screens) {
ScreenPlayUtil.removeAll(scheduler, screens);
return BackBOUtil.defaultBackBO();
} }

关于使用quartz动态增删改定时任务的更多相关文章

  1. 实现Quartz的动态增删改查

    1. Maven依赖 <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId> ...

  2. SSM 整合 quartz JDBC方式实现job动态增删改查记录

    虽然网上有很多资料,但是都不够系统,本文记录下自己的整合过程. 1. 搭建一个SSM项目,此处略. 2. 按照quartz官方要求,建立quartz相关的数据库和表,相关sql语句如下: /* Nav ...

  3. jquery表格动态增删改及取数据绑定数据完整方案

    一 前言 上一篇Jquery遮罩插件,想罩哪就罩哪! 结尾的预告终于来了. 近期参与了一个针对内部员工个人信息收集的系统,其中有一个需求是在填写各个相关信息时,需要能动态的增加行当时公司有自己的解决方 ...

  4. jQuery动态增删改查表格信息,可左键/右键提示

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. JavaScript动态增删改表格数据

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  6. mybatis的动态增删改查

    1.动态SQL片段 通过SQL片段达到代码复用 <!-- 动态条件分页查询 --> <sql id="sql_count"> select count(*) ...

  7. fullcalendar日历插件的使用并动态增删改查

    我上个项目是做了一个关于教育方面的web端页面,其中的课程表就要用到fullcalendar日历插件,刚开始也是不会用,因为以前也没用过,后面也是看官方文档,问同事,最后完成了这个课程表,个人感觉fu ...

  8. BootStrap table动态增删改表格内数据

    1:添加一个[操作]列   { title: "操作", align: 'center', valign: 'middle', width: 160, // 定义列的宽度,单位为像 ...

  9. 使用BindingList来实现DataGridview数据源为list时的动态增删改

    当DataGridview的数据源list的时候,对list进行操作后重新绑定,数据并不会更新 使用BindingList能很好的解决这个问题(framework2.0新增) 例如,使用list时候的 ...

随机推荐

  1. vs2012编译ffmpeg

    从官方网站down下来的ffmpeg没有pdb文件不方便调试,为此使用VS2012编译ffmpeg. 编译步骤: 一.安装MinGW,具体的安装方法上一篇文章已经有介绍这里不在赘述. 二.下载文件并放 ...

  2. TIBCO RV

    http://blog.csdn.net/tiercel2008/article/details/6799952

  3. Django-models-m2m

    在Django的orm中,如果有多对多的字段,那么他的第三张表时自己生成的,参考官方文档发现第三张表可以自己写↓: 而且第三张表好像是可以自定制的 from django.db import mode ...

  4. jmeter后置处理器之正則表達式提取器

    新浪围脖>@o蜗牛快跑o    使用这个组件时,注意使用带分组的正則表達式 使用正则分组方便提取干净数据.以免再次处理数据字符串 正則表達式在线工具推荐:点击打开链接 正則表達式语法參考:点击打 ...

  5. 多项式相乘快速算法原理及相应C代码实现---用到fft

    最近认真研究了一下算法导论里面的多项式乘法的快速计算问题,主要是用到了FFT,自己也实现了一下,总结如下. 1.多项式乘法 两个多项式相乘即为多项式乘法,例如:3*x^7+4*x^5+1*x^2+5与 ...

  6. LeetCode: Binary Tree Postorder Traversal [145]

    [题目] Given a binary tree, return the postorder traversal of its nodes' values. For example: Given bi ...

  7. find命令用法

    关于查找 文件查找:     locate非实时查找:根据索引查找     find实时查找:根据文件的各种属性去找到相对应文件     根据文件的各种属性去找到相对应文件 文本搜索:     gre ...

  8. LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

    1 什么是“module machine type” 这个是当前工程要链接的静态库的target machine type. 2 什么是“target machine type” 这个是当前工程生成的 ...

  9. 一起来学linux:磁盘与文件系统:

    对于文件系统来说,windows上最长用的就是FAT32和NTFS.在Linux上时候用的是Ext2.在linux中,文件权限与文件属性这两部分会被存储在不同的块,权限与权限放置到inode中,实际数 ...

  10. 3.改变 HTML 内容

    ①x=document.getElementById("demo") //查找元素 ②x.innerHTML="Hello JavaScript"; //改变内 ...