关于使用quartz动态增删改定时任务
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动态增删改定时任务的更多相关文章
- 实现Quartz的动态增删改查
1. Maven依赖 <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId> ...
- SSM 整合 quartz JDBC方式实现job动态增删改查记录
虽然网上有很多资料,但是都不够系统,本文记录下自己的整合过程. 1. 搭建一个SSM项目,此处略. 2. 按照quartz官方要求,建立quartz相关的数据库和表,相关sql语句如下: /* Nav ...
- jquery表格动态增删改及取数据绑定数据完整方案
一 前言 上一篇Jquery遮罩插件,想罩哪就罩哪! 结尾的预告终于来了. 近期参与了一个针对内部员工个人信息收集的系统,其中有一个需求是在填写各个相关信息时,需要能动态的增加行当时公司有自己的解决方 ...
- jQuery动态增删改查表格信息,可左键/右键提示
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- JavaScript动态增删改表格数据
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- mybatis的动态增删改查
1.动态SQL片段 通过SQL片段达到代码复用 <!-- 动态条件分页查询 --> <sql id="sql_count"> select count(*) ...
- fullcalendar日历插件的使用并动态增删改查
我上个项目是做了一个关于教育方面的web端页面,其中的课程表就要用到fullcalendar日历插件,刚开始也是不会用,因为以前也没用过,后面也是看官方文档,问同事,最后完成了这个课程表,个人感觉fu ...
- BootStrap table动态增删改表格内数据
1:添加一个[操作]列 { title: "操作", align: 'center', valign: 'middle', width: 160, // 定义列的宽度,单位为像 ...
- 使用BindingList来实现DataGridview数据源为list时的动态增删改
当DataGridview的数据源list的时候,对list进行操作后重新绑定,数据并不会更新 使用BindingList能很好的解决这个问题(framework2.0新增) 例如,使用list时候的 ...
随机推荐
- 【LeetCode】Word Break 解题报告
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...
- vim 参数文件配置
下面是我配置的遇到问题不能修改配置文件时的解决方案 1 /usr/share/vim/vimrc 2 这个是系统型的vimrc配置文件,为了保证vim的正常使用,一般并不会修改这个文件, 而是应该在你 ...
- CSS入门学习
一.What? CSS的全称是CascadingStyle Sheet,汉语意思是"级联样式表".通常又称为"风格样式表(StyleSheet)".它是用来进行 ...
- Leetcode 001-twosum
#Given an array of integers, return indices of the two numbers such that they add up to a specific t ...
- xlua学习过程遇到的问题,以后通了之后可能就不是问题了。但是还是有记录的必要。
//2.加载lua文件,这里这种方式只能够加载Resources文件夹下面的,并且是lua.txt类型的文件,感觉没啥乱用. //文档你说的是Resources文件夹下面的才需要加txt后缀,那么就是 ...
- EasyPusher安卓Android手机直播推送之RTSP流媒体协议流程
EasyPusher移动端推送同我们平时用的RTSP直播推送流程一样,都是采用标准RTSP/RTP推送流程:ANNOUNCE->SETUP->PLAY->RTP/RTCP->T ...
- java基础知识查漏 三
一.Servlet 和Jsp的生命周期 1.Servlet生命周期 Servlet是运行在Servlet容器(有时候也叫Servlet引擎,是web服务器和应用程序服务器的一部分,用于在发 ...
- Redis 单例、主从模式、sentinel 以及集群的配置方式及优缺点对比(转)
摘要: redis作为一种NoSql数据库,其提供了一种高效的缓存方案,本文则主要对其单例,主从模式,sentinel以及集群的配置方式进行说明,对比其优缺点,阐述redis作为一种缓存框架的高可用性 ...
- Android笔记之强大的buildConfigField
在进行项目开发或维护时,经常会遇到调试和发布所用到的参数值不一致的情况 例如,服务器会分测试和正式,为了能方便地更改(自动更换)服务器地址,buildConfigField就派上用场了 以前都是手动更 ...
- js 单例模式的实现方式----闭包和构造函数内部判断
闭包: var singleton = function( fn ){ var result; return function(){ return result || ( result = fn .a ...