Spring4整合quartz2.2.3,quartz动态任务
Spring4整合quartz2.2.3,quartz动态任务
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年9月6日
http://fanshuyao.iteye.com/
quartz下载
http://www.quartz-scheduler.org/downloads/
一、quartz动态任务管理类:
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Set;
- import org.quartz.CronScheduleBuilder;
- import org.quartz.CronTrigger;
- import org.quartz.Job;
- import org.quartz.JobBuilder;
- import org.quartz.JobDetail;
- import org.quartz.JobExecutionContext;
- import org.quartz.JobKey;
- import org.quartz.Scheduler;
- import org.quartz.SchedulerException;
- import org.quartz.Trigger;
- import org.quartz.TriggerBuilder;
- import org.quartz.TriggerKey;
- import org.quartz.impl.matchers.GroupMatcher;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import cn.imovie.common.utils.CC;
- import cn.imovie.common.utils.JasonUtils;
- import cn.imovie.common.utils.SpringUtils;
- import cn.imovie.entity.task.ScheduleJob;
- import cn.imovie.service.ScheduleJobService;
- public class SchedulerManage {
- private Logger log = LoggerFactory.getLogger(SchedulerManage.class);
- private Scheduler scheduler = (Scheduler) SpringUtils.getBeanById("scheduler");
- @Autowired
- private ScheduleJobService scheduleJobService;
- /**
- * 新增任务
- * @param scheduleJob
- */
- @SuppressWarnings("unchecked")
- public void addJob(ScheduleJob scheduleJob){
- TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
- try {
- //任务触发
- CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
- if (null == trigger) {
- JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(scheduleJob.getClazz()))
- .withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).build();
- jobDetail.getJobDataMap().put("scheduleJob", scheduleJob);
- CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
- /*withMisfireHandlingInstructionDoNothing
- ——不触发立即执行
- ——等待下次Cron触发频率到达时刻开始按照Cron频率依次执行
- withMisfireHandlingInstructionIgnoreMisfires
- ——以错过的第一个频率时间立刻开始执行
- ——重做错过的所有频率周期后
- ——当下一次触发频率发生时间大于当前时间后,再按照正常的Cron频率依次执行
- withMisfireHandlingInstructionFireAndProceed
- ——以当前时间为触发频率立刻触发一次执行
- ——然后按照Cron频率依次执行*/
- trigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withSchedule(cronScheduleBuilder.withMisfireHandlingInstructionDoNothing()).build();
- scheduler.scheduleJob(jobDetail, trigger);
- log.info(CC.LOG_PREFIX + "新增任务:"+JasonUtils.Object2String(scheduleJob));
- }else {
- // Trigger已存在,那么更新相应的定时设置
- //表达式调度构建器
- CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
- //按新的cronExpression表达式重新构建trigger
- trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder.withMisfireHandlingInstructionDoNothing()).build();
- //按新的trigger重新设置job执行
- scheduler.rescheduleJob(triggerKey, trigger);
- log.info(CC.LOG_PREFIX + "任务"+JasonUtils.Object2String(scheduleJob)+"已经存在,更新trigger");
- }
- //scheduleJobService.save(req, sysUserInSession, scheduleJob);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 暂停任务
- * @param scheduleJob
- */
- public void pauseJob(ScheduleJob scheduleJob){
- JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
- try {
- scheduler.pauseJob(jobKey);
- log.info(CC.LOG_PREFIX + "暂停任务:"+JasonUtils.Object2String(scheduleJob));
- } catch (SchedulerException e) {
- e.printStackTrace();
- }
- }
- /**
- * 暂停全部任务
- */
- public void pauseAll(){
- try {
- scheduler.pauseAll();
- log.info(CC.LOG_PREFIX + "暂停所有任务");
- } catch (SchedulerException e) {
- e.printStackTrace();
- }
- }
- /**
- * 恢复任务
- * @param scheduleJob
- */
- public void resumeJob(ScheduleJob scheduleJob){
- JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
- try {
- scheduler.resumeJob(jobKey);
- log.info(CC.LOG_PREFIX + "恢复任务:"+JasonUtils.Object2String(scheduleJob));
- } catch (SchedulerException e) {
- e.printStackTrace();
- }
- }
- /**
- * 恢复所有任务
- */
- public void resumeAll(){
- try {
- scheduler.resumeAll();
- log.info(CC.LOG_PREFIX + "恢复所有任务");
- } catch (SchedulerException e) {
- e.printStackTrace();
- }
- }
- /**
- * 删除任务后,所对应的trigger也将被删除
- * @param scheduleJob
- */
- public void deleteJob(ScheduleJob scheduleJob){
- JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
- try {
- scheduler.pauseJob(jobKey);//先暂停任务
- scheduler.deleteJob(jobKey);//再删除任务
- log.info(CC.LOG_PREFIX + "删除任务:"+JasonUtils.Object2String(scheduleJob));
- } catch (SchedulerException e) {
- e.printStackTrace();
- }
- }
- /**
- * 立即运行任务
- * @param scheduleJob
- */
- public void triggerJob(ScheduleJob scheduleJob){
- JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
- try {
- scheduler.triggerJob(jobKey);
- log.info(CC.LOG_PREFIX + "运行任务:"+JasonUtils.Object2String(scheduleJob));
- } catch (SchedulerException e) {
- e.printStackTrace();
- }
- }
- /**
- * 更新任务的时间表达式
- * @param scheduleJob
- */
- public void updateJob(ScheduleJob scheduleJob){
- try {
- TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
- //获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
- CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
- //表达式调度构建器
- CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
- //按新的cronExpression表达式重新构建trigger
- trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder.withMisfireHandlingInstructionDoNothing()).build();
- //按新的trigger重新设置job执行
- scheduler.rescheduleJob(triggerKey, trigger);
- log.info(CC.LOG_PREFIX + "更新任务:"+JasonUtils.Object2String(scheduleJob));
- } catch (SchedulerException e) {
- e.printStackTrace();
- }
- }
- /**
- * 获取quartz调度器的计划任务
- * @return
- */
- public List<ScheduleJob> getScheduleJobList(){
- List<ScheduleJob> jobList = null;
- try {
- GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
- Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
- jobList = new ArrayList<ScheduleJob>();
- for (JobKey jobKey : jobKeys) {
- List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
- for (Trigger trigger : triggers) {
- ScheduleJob job = new ScheduleJob();
- job.setJobName(jobKey.getName());
- job.setJobGroup(jobKey.getGroup());
- job.setClazz(jobKey.getClass().toString());
- job.setJobDesc("触发器:" + trigger.getKey());
- Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
- job.setJobStatus(triggerState.name());
- if (trigger instanceof CronTrigger) {
- CronTrigger cronTrigger = (CronTrigger) trigger;
- String cronExpression = cronTrigger.getCronExpression();
- job.setCronExpression(cronExpression);
- }
- jobList.add(job);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return jobList;
- }
- /**
- * 获取quartz调度器的运行任务
- * @return
- */
- public List<ScheduleJob> getScheduleJobRunningList(){
- List<ScheduleJob> jobList = null;
- try {
- List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
- jobList = new ArrayList<ScheduleJob>(executingJobs.size());
- for (JobExecutionContext executingJob : executingJobs) {
- ScheduleJob job = new ScheduleJob();
- JobDetail jobDetail = executingJob.getJobDetail();
- JobKey jobKey = jobDetail.getKey();
- Trigger trigger = executingJob.getTrigger();
- job.setJobName(jobKey.getName());
- job.setJobGroup(jobKey.getGroup());
- job.setClazz(jobKey.getClass().toString());
- job.setJobDesc("触发器:" + trigger.getKey());
- Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
- job.setJobStatus(triggerState.name());
- if (trigger instanceof CronTrigger) {
- CronTrigger cronTrigger = (CronTrigger) trigger;
- String cronExpression = cronTrigger.getCronExpression();
- job.setCronExpression(cronExpression);
- }
- jobList.add(job);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return jobList;
- }
- public Scheduler getScheduler() {
- return scheduler;
- }
- public void setScheduler(Scheduler scheduler) {
- this.scheduler = scheduler;
- }
- }
注意事项:
1、SchedulerFactoryBean 在spring.xml配置了,但不能直接注入,就算加上@Component注解也不行,所以使用SpringUtils 工具类获取。
- <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
2、获取到的SchedulerFactoryBean 并不是SchedulerFactoryBean,而是scheduler
- private Scheduler scheduler = (Scheduler) SpringUtils.getBeanById("scheduler");
二、ScheduleJob 类:可以保存计划任务的信息,也可以做为实体参数
- public class ScheduleJob implements Serializable{
- private Long scheduleJobId;
- /** 任务名称 */
- private String jobName;
- /** 任务分组 */
- private String jobGroup;
- /** 定时任务对应的类(包括包路径),如:cn.imovie.manage.task.job.TicketMoneyLessThanNormalWarn */
- private String clazz;
- /** 任务状态:1禁用 2启用 3删除*/
- private String jobStatus;
- /** 任务运行时间表达式 */
- private String cronExpression;
- /** 任务描述 */
- private String jobDesc;
- private Long createMan;
- private Date createTime;
- private Long updateMan;
- private Date updateTime;
- // 非持久化属性
- private String createManText;
- private String updateManText;
- public Long getScheduleJobId() {
- return scheduleJobId;
- }
- public void setScheduleJobId(Long scheduleJobId) {
- this.scheduleJobId = scheduleJobId;
- }
- public String getJobName() {
- return jobName;
- }
- public void setJobName(String jobName) {
- this.jobName = jobName;
- }
- public String getJobGroup() {
- return jobGroup;
- }
- public void setJobGroup(String jobGroup) {
- this.jobGroup = jobGroup;
- }
- public String getClazz() {
- return clazz;
- }
- public void setClazz(String clazz) {
- this.clazz = clazz;
- }
- public String getJobStatus() {
- return jobStatus;
- }
- public void setJobStatus(String jobStatus) {
- this.jobStatus = jobStatus;
- }
- public String getCronExpression() {
- return cronExpression;
- }
- public void setCronExpression(String cronExpression) {
- this.cronExpression = cronExpression;
- }
- public String getJobDesc() {
- return jobDesc;
- }
- public void setJobDesc(String jobDesc) {
- this.jobDesc = jobDesc;
- }
- public Long getCreateMan() {
- return createMan;
- }
- public void setCreateMan(Long createMan) {
- this.createMan = createMan;
- }
- public Date getCreateTime() {
- return createTime;
- }
- public void setCreateTime(Date createTime) {
- this.createTime = createTime;
- }
- public Long getUpdateMan() {
- return updateMan;
- }
- public void setUpdateMan(Long updateMan) {
- this.updateMan = updateMan;
- }
- public Date getUpdateTime() {
- return updateTime;
- }
- public void setUpdateTime(Date updateTime) {
- this.updateTime = updateTime;
- }
- @Transient
- public String getCreateManText() {
- return createManText;
- }
- public void setCreateManText(String createManText) {
- this.createManText = createManText;
- }
- @Transient
- public String getUpdateManText() {
- return updateManText;
- }
- public void setUpdateManText(String updateManText) {
- this.updateManText = updateManText;
- }
- }
三、Spring.xml 文件配置
- <!-- 定时任务配置 start -->
- <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
- <property name="dataSource" ref="dataSource"></property>
- <!--可选,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 -->
- <property name="overwriteExistingJobs" value="true" />
- <!--必须的,QuartzScheduler 延时启动,应用启动完后 QuartzScheduler 再启动 -->
- <property name="startupDelay" value="10" />
- <!-- 设置自动启动 -->
- <property name="autoStartup" value="true" />
- <property name="applicationContextSchedulerContextKey" value="applicationContextKey" />
- <property name="configLocation" value="classpath:spring-quartz.properties" />
- </bean>
- <bean id="schedulerManage" class="cn.imovie.manage.task.SchedulerManage"></bean>
- <!-- 定时任务配置 end -->
四、spring-quartz.properties 文件配置:
- #配置见:http://www.quartz-scheduler.org/documentation/quartz-2.2.x/configuration/ConfigJDBCJobStoreClustering.html
- #============================================================================
- # Configure Main Scheduler Properties
- #============================================================================
- org.quartz.scheduler.instanceName = MyClusteredScheduler
- org.quartz.scheduler.instanceId = AUTO
- #============================================================================
- # Configure ThreadPool
- #============================================================================
- org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
- org.quartz.threadPool.threadCount = 25
- org.quartz.threadPool.threadPriority = 5
- #============================================================================
- # Configure JobStore
- #============================================================================
- org.quartz.jobStore.misfireThreshold = 60000
- org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
- org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
- org.quartz.jobStore.useProperties = false
- org.quartz.jobStore.dataSource = myDS
- org.quartz.jobStore.tablePrefix = QRTZ_
- org.quartz.jobStore.isClustered = true
- org.quartz.jobStore.clusterCheckinInterval = 20000
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年9月6日
http://www.cnblogs.com/fanshuyao/
Spring4整合quartz2.2.3,quartz动态任务的更多相关文章
- Spring4 Quartz2 动态任务,Spring4整合quartz2.2.3简单动态任务
Spring4 Quartz2 动态任务 Spring4整合quartz2.2.3简单动态任务, Quartz2.2.3简单动态定时任务二, SimpleScheduleBuilder简单定时任务 ...
- Spring定时任务,Spring4整合quartz2.2,quartz-scheduler定时任务
Spring4整合quartz2.2,quartz-scheduler定时任务,Spring定时任务 >>>>>>>>>>>>& ...
- Quartz动态添加,修改,删除任务(暂停,任务状态,恢复,最近触发时间)
首页 博客 学院 下载 图文课 论坛 APP 问答 商城 VIP会员 活动 招聘 ITeye GitChat 写博客 小程序 消息 登录注册 关闭 quartz_Cron表达式一分钟教程 09-05 ...
- Spring整合quartz2.2.3总结,quartz动态定时任务,Quartz定时任务集群配置
Spring整合quartz2.2.3总结,quartz动态定时任务,Quartz定时任务集群配置 >>>>>>>>>>>>&g ...
- Spring3 整合Quartz2 实现定时任务
一.Quartz简介 Quartz是一个由James House创立的开源项目,是一个功能强大的作业调度工具,可以计划的执行任务,定时.循环或在某一个时间来执行我们需要做的事,这可以给我们工作上带来很 ...
- Quartz动态添加、修改和删除定时任务
任务调度开源框架Quartz动态添加.修改和删除定时任务 Quartz 是个开源的作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制.Quartz框架包含了调度器监听.作业和触 ...
- (六)Spring4 整合Hibernate4,Struts2
第一节:S2SH 整合所需Jar 包 Struts2.3.16,Spring4.0.6,Hibernate4.3.5 整合所需jar 包: Struts2.3.16 jar 包 Spring4.0.6 ...
- Spring4整合Hibernate5时不能自动生成表结构
© 版权声明:本文为博主原创文章,转载请注明出处 1.问题描述: Spring4整合Hibernate5时,不再使用hibernate.cfg.xml,将其内容整合到Spring配置文件中,启动后不能 ...
- 【Java Web开发学习】Spring4整合thymeleaf视图解析
[Java Web开发学习]Spring4整合thymeleaf视图解析 目录 1.简单介绍2.简单例子 转载:https://www.cnblogs.com/yangchongxing/p/9111 ...
随机推荐
- 内核对象kobject和sysfs(2)——kref分析
内核对象kobject和sysfs(2)--kref分析 在介绍ref之前,先贴上kref的结构: struct kref { atomic_t refcount; }; 可以看到,kref只是包含一 ...
- 智慧航空AI大赛-阿里云算法大赛总结 第一赛季总结
[以前的文章]最后一公里极速配送 - 阿里云算法大赛总结 总结一下新的教训 1.由于都是NP难题,获得最优解用常规的方法非常困难,对于不是算法科班出身的人来说,首先应该到网络上寻找一下论文,是否有一些 ...
- maven单元测试设置代理
背景 环境需要设置代理才能够访问外部网络,如果只是运行java程序来访问网络,我们可以通过java -jar test.jar -DproxyHost=proxy_ip -DproxyPort=pro ...
- css简单实现五角星评分、点赞收藏、展示评分(半颗星、1/3颗星)
1.前言 之前做的好几个项目中,都会遇到打分,评分,点赞这样的需求,写了很多次,每次需要再写的时候,就会翻出之前写过的代码,然后copy过来.总觉得这样的话没有进步,没有把知识放进脑袋里,所以,自己花 ...
- 在Navicat 中给Mysql中的某字段添加前缀00
第一次分享心得,希望大家多多关注. 我遇到的情况是这样的,在Navicat中某表的varchar字段内容长度不够5的在内容前面添加‘0’:如字段内容是 101 我就要改成00101: 其中有2个难点: ...
- swift UIButton边框添加阴影效果
btn.layer.shadowOpacity = 0.8 //阴影区域透明度 btn.layer.shadowColor = UIColor.black.cgColor // 阴影区域颜色 btn. ...
- 电机PID调试注意(待补充)
1.速度传感器 返回值要处理好,要和目标值同一单位,这样方便以后的计算 2.PID初始化要准确 3.输出给定要设定一个阈值,防止电机转速太大.
- Java Collection(转载)
在 Java2中,有一套设计优良的接口和类组成了Java集合框架Collection,使程序员操作成批的数据或对象元素极为方便.这些接口和类有很多对 抽象数据类型操作的API,而这是我们常用的且在数据 ...
- 案例:Standby RAC遭遇ORA-1157,1111,1110导致实例crash处理
案例:Standby RAC遭遇ORA-1157,1111,1110导致实例crash处理 环境:RHEL 6.5 + Oracle RAC 11.2.0.4 + Dataguard 今天在实验环境的 ...
- nodejs 文件读取一行
作者QQ:1095737364 QQ群:123300273 欢迎加入! 废话没有,直接上代码: app.get('/company', function (req, res, nex ...