quartz.properties配置: http://orange5458.iteye.com/blog/1170777
quartz集群调度机制调研及源码分析: http://www.cnblogs.com/davidwang456/p/4205237.html
深入解读Quartz的原理: http://lavasoft.blog.51cto.com/62575/181907/
quartz源码解析: http://www.cnblogs.com/davidwang456/p/3878625.html
任务调度开源框架Quartz动态添加、修改和删除定时任务 : http://www.tuicool.com/articles/Ff6F7v
新建JOb
package job; import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.TriggerKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SimpleJob implements Job { private static int jobCount = 0; Logger log = LoggerFactory.getLogger(SimpleJob.class); @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 此任务仅打印日志便于调试、观察 log.info("==================:"+this.getClass().getName() + " was just triggered..."); JobKey jobKey = context.getJobDetail().getKey(); TriggerKey triggerKey = context.getTrigger().getKey(); Scheduler scheduler = context.getScheduler(); //启动线程监听触发器的状态 new Thread(new SchedEventLister(triggerKey,scheduler)).start(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); log.info("任务分组名称: " + jobKey.getGroup()+",任务名称: " + jobKey.getName()+",触发器组名称: " + triggerKey.getGroup()+ ",触发器名称: "+ triggerKey.getName()+" 执行时间: " + sdf.format(new Date()) + ",计数: " + (++jobCount)) ; //如果任务执行超过15次就结束它 /* if(jobCount > 3){ log.warn("结束任务..."); try { //Delete the identified Job from the Scheduler - and any associated Triggers. //从调度器中删除这个唯一任务时同时会删除相关联的触发器^_^ scheduler.deleteJob(jobKey); } catch (SchedulerException e) { e.printStackTrace(); } }*/ if(jobCount == 2 ){ //暂停触发器 try { scheduler.pauseTrigger(triggerKey); log.warn("已经暂停了触发器...,触发器组名: " + triggerKey.getGroup() + ",触发器名称: " + triggerKey.getName()); } catch (SchedulerException e) { throw new RuntimeException(e); } } if(jobCount == 4){ try { scheduler.pauseTrigger(triggerKey); // 停止触发器 scheduler.unscheduleJob(triggerKey);//移除触发器 scheduler.pauseJob(jobKey);// 停止任务 scheduler.deleteJob(jobKey);// 删除任务 log.error("正在停止并且移除触发器...,触发器组名: " + triggerKey.getGroup() + ",触发器名称: " + triggerKey.getName()); } catch (SchedulerException e) { throw new RuntimeException(e); } } } }
Job监听器:
package job; import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SchedEventLister implements Runnable{ private static Logger log = LoggerFactory.getLogger(SchedEventLister.class); private Scheduler sched = null; private TriggerKey triggerKey = null; public SchedEventLister(TriggerKey triggerKey,Scheduler sched) { log.info("触发器线程监听启动...."); this.triggerKey = triggerKey; this.sched = sched; } @Override public void run() { log.info("触发器线程监听中。。。。" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") .format(new Date())); // 获取当前触发器的状态 Trigger.TriggerState ts = null; try { ts = sched.getTriggerState(triggerKey); } catch (SchedulerException e) { e.printStackTrace(); } // 如果为暂停状态就恢复 if (ts == Trigger.TriggerState.PAUSED) { // 暂停10秒在恢复 try { log.warn("暂停当前线程5秒钟后在恢复触发器...,触发器组名: " + triggerKey.getGroup() + ",触发器名称: " + triggerKey.getName()); Thread.sleep(5L * 1000L); } catch (InterruptedException e1) { e1.printStackTrace(); } // 恢复触发器 log.warn("正在恢复了触发器...,触发器组名: " + triggerKey.getGroup() + ",触发器名称: " + triggerKey.getName()); try { sched.resumeTrigger(triggerKey); } catch (SchedulerException e) { throw new RuntimeException(e); } } else if (ts == Trigger.TriggerState.NORMAL) { log.info("触发器线程监听中。。。。,状态:正常 "); } else if (ts == Trigger.TriggerState.NONE) { log.info("触发器线程监听中。。。。,状态:没有触发器 "); } else if (ts == Trigger.TriggerState.ERROR) { log.info("触发器线程监听中。。。。,状态:错误 "); } else if (ts == Trigger.TriggerState.BLOCKED) { log.info("触发器线程监听中。。。。,状态:堵塞 "); } } }
简单触发器测试:
package job; import java.util.concurrent.TimeUnit; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleScheduleBuilder; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class testSimpleTrriger { private static Logger logger = LoggerFactory.getLogger(testSimpleTrriger.class); public static void main(String[] args) { try { // 获取Scheduler实例 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // 具体任务 JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("SimpleJob", "Job-Group-Simple").build(); // 触发时间点 SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever(); Trigger trigger = TriggerBuilder.newTrigger().withIdentity("SimpleTrigger", "Trriger-Group-Simple"). startNow().withSchedule(simpleScheduleBuilder).build(); // 交由Scheduler安排触发 scheduler.scheduleJob(job, trigger); scheduler.start(); try { TimeUnit.MINUTES.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } // 关闭Scheduler scheduler.shutdown(); } catch (SchedulerException se) { logger.error(se.getMessage(), se); } } }
CronTrigger触发器测试:
package job; import java.util.concurrent.TimeUnit; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestCronTrriger { private static Logger logger = LoggerFactory.getLogger(testSimpleTrriger.class); public static void main(String[] args) { try { // 获取Scheduler实例 SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler cronScheduler = schedulerFactory.getScheduler(); // 具体任务 JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("SimpleJob", "Job-Group-Simple").build(); // 触发时间点 // 交由Scheduler安排触发 String cronExpression = "0/5 * * * * ?"; // 每分钟的30s起,每5s触发任务 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression); CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("SimpleTrigger", "Trriger-Group-Simple") .withSchedule(cronScheduleBuilder) .build(); cronScheduler.scheduleJob(job, cronTrigger); cronScheduler.start(); try { /* 为观察程序运行,此设置主程序睡眠2分钟才继续往下运行(因下一个步骤是“关闭Scheduler”) */ TimeUnit.MINUTES.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } // 关闭Scheduler cronScheduler.shutdown(); } catch (SchedulerException se) { logger.error(se.getMessage(), se); } } }
上面两个测试类只是测试触发器种类不同而已,使劲处理的job是相同的
测试结果:
九月 05, 2016 9:41:00 上午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Using default implementation for ThreadExecutor
九月 05, 2016 9:41:00 上午 org.quartz.simpl. SimpleThreadPool initialize
信息: Job execution threads will use class loader of thread: main
九月 05, 2016 9:41:00 上午 org.quartz.core.SchedulerSignalerImpl
信息: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
九月 05, 2016 9:41:00 上午 org.quartz.core.QuartzScheduler
信息: Quartz Scheduler v.2.2.1 created.
九月 05, 2016 9:41:00 上午 org.quartz.simpl.RAMJobStore initialize
信息: RAMJobStore initialized.
九月 05, 2016 9:41:00 上午 org.quartz.core.QuartzScheduler initialize
信息: Scheduler meta-data: Quartz Scheduler (v2.2.1) 'DefaultQuartzScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
九月 05, 2016 9:41:00 上午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
###如果配置了quartz.properties则从quartz.properties文中加载相关配置信息
九月 05, 2016 9:41:00 上午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler version: 2.2.1
九月 05, 2016 9:41:00 上午 org.quartz.core.QuartzScheduler start
信息: Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
#第一次执行
九月 05, 2016 9:41:00 上午 job.SimpleJob execute
信息: ==================:job.SimpleJob was just triggered...
九月 05, 2016 9:41:00 上午 job.SchedEventLister
信息: 触发器线程监听启动....
九月 05, 2016 9:41:00 上午 job.SchedEventLister run
信息: 触发器线程监听中。。。。2016-09-05 09:41:00
九月 05, 2016 9:41:00 上午 job.SimpleJob execute
信息: 任务分组名称: Job-Group-Simple,任务名称: SimpleJob,触发器组名称: Trriger-Group-Simple,触发器名称: SimpleTrigger 执行时间: 2016-09-05 09:41:00,计数: 1
九月 05, 2016 9:41:00 上午 job.SchedEventLister run
信息: 触发器线程监听中。。。。,状态:正常
#第二次执行, 暂停5秒钟,再恢复
九月 05, 2016 9:41:05 上午 job.SimpleJob execute
信息: ==================:job.SimpleJob was just triggered...
九月 05, 2016 9:41:05 上午 job.SchedEventLister
信息: 触发器线程监听启动....
九月 05, 2016 9:41:05 上午 job.SimpleJob execute
信息: 任务分组名称: Job-Group-Simple,任务名称: SimpleJob,触发器组名称: Trriger-Group-Simple,触发器名称: SimpleTrigger 执行时间: 2016-09-05 09:41:05,计数: 2
九月 05, 2016 9:41:05 上午 job.SchedEventLister run
信息: 触发器线程监听中。。。。2016-09-05 09:41:05
九月 05, 2016 9:41:05 上午 job.SimpleJob execute
警告: 已经暂停了触发器...,触发器组名: Trriger-Group-Simple,触发器名称: SimpleTrigger
九月 05, 2016 9:41:05 上午 job.SchedEventLister run
警告: 暂停当前线程5秒钟后在恢复触发器...,触发器组名: Trriger-Group-Simple,触发器名称: SimpleTrigger
九月 05, 2016 9:41:10 上午 job.SchedEventLister run
警告: 正在恢复了触发器...,触发器组名: Trriger-Group-Simple,触发器名称: SimpleTrigger
#第三次执行
九月 05, 2016 9:41:10 上午 job.SimpleJob execute
信息: ==================:job.SimpleJob was just triggered...
九月 05, 2016 9:41:10 上午 job.SchedEventLister
信息: 触发器线程监听启动....
九月 05, 2016 9:41:10 上午 job.SimpleJob execute
信息: 任务分组名称: Job-Group-Simple,任务名称: SimpleJob,触发器组名称: Trriger-Group-Simple,触发器名称: SimpleTrigger 执行时间: 2016-09-05 09:41:10,计数: 3
九月 05, 2016 9:41:10 上午 job.SchedEventLister run
信息: 触发器线程监听中。。。。2016-09-05 09:41:10
九月 05, 2016 9:41:10 上午 job.SchedEventLister run
信息: 触发器线程监听中。。。。,状态:正常
#第四次执行
九月 05, 2016 9:41:15 上午 job.SimpleJob execute
信息: ==================:job.SimpleJob was just triggered...
九月 05, 2016 9:41:15 上午 job.SchedEventLister
信息: 触发器线程监听启动....
九月 05, 2016 9:41:15 上午 job.SimpleJob execute
信息: 任务分组名称: Job-Group-Simple,任务名称: SimpleJob,触发器组名称: Trriger-Group-Simple,触发器名称: SimpleTrigger 执行时间: 2016-09-05 09:41:15,计数: 4
九月 05, 2016 9:41:15 上午 job.SchedEventLister run
信息: 触发器线程监听中。。。。2016-09-05 09:41:15
九月 05, 2016 9:41:15 上午 job.SimpleJob execute
严重: 正在停止并且移除触发器...,触发器组名: Trriger-Group-Simple,触发器名称: SimpleTrigger
九月 05, 2016 9:41:15 上午 job.SchedEventLister run
信息: 触发器线程监听中。。。。,状态:没有触发器
九月 05, 2016 9:43:00 上午 org.quartz.core.QuartzScheduler shutdown
信息: Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.
九月 05, 2016 9:43:00 上午 org.quartz.core.QuartzScheduler standby
信息: Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.
九月 05, 2016 9:43:00 上午 org.quartz.core.QuartzScheduler shutdown
信息: Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.
quartz.properties文件:
#线程池实现类
org.quartz.threadPool.class =org.quartz.simpl.SimpleThreadPool
#线程池数
org.quartz.threadPool.threadCount = 5
#线程池优先级
org.quartz.threadPool.threadPriority = 5
#线程池运行模式守后,还是前台
org.quartz.threadPool.makeThreadsDaemons=false
###线程池配置的继承属性
org.quartz.threadPool.threadsInheritGroupOfInitializingThread=true
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true
###保存job调度执行信息到RAM,这种方式当应用下次重启时,job调度信息容易丢失
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
org.quartz.jobStore.misfireThreshold = 60000
############.JobStoreTX,是将job调度信息保存到RDB中,应用重启时可以重新调度job
#org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#org.quartz.jobStore.dataSource=test
#org.quartz.dataSource.test.driver=com.mysql.jdbc.Driver
#org.quartz.dataSource.test.URL=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=utf8&characterSetResults\=utf8
#org.quartz.dataSource.test.user=root
#org.quartz.dataSource.test.password=123456
#org.quartz.dataSource.test.maxConnections=20