quartz 2.2.3 自带示例源码解读example1~example5

目录(?)[+]

Example1 第一个quartz示例

  1. public class HelloJob implements Job {  
  2.       
  3.     private static Logger _log = LoggerFactory.getLogger(HelloJob.class);  
  4.   
  5.     public HelloJob() {  
  6.     }  
  7.       
  8.     @Override  
  9.     public void execute(JobExecutionContext context)  
  10.             throws JobExecutionException {  
  11.         _log.info("Hello World! - " + new Date());  
  12.     }  
  13. }  
  14.   
  15.   
  16. public class SimpleExample {  
  17.     public void run() throws Exception {  
  18.         Logger log = LoggerFactory.getLogger(SimpleExample.class);  
  19.           
  20.         log.info("------- Initializing ----------------------");  
  21.           
  22.         SchedulerFactory sf = new StdSchedulerFactory();  
  23.         Scheduler sched = sf.getScheduler();  
  24.           
  25.         log.info("------- Initialization Complete -----------");  
  26.           
  27.         // 下一个整分钟  
  28.         Date runTime = DateBuilder.evenMinuteDate(new Date());  
  29.           
  30.         log.info("------- Scheduling Job  -------------------");  
  31.           
  32.         JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1""group").build();  
  33.         Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1""group1").startAt(runTime).build();  
  34.         sched.scheduleJob(job, trigger);  
  35.           
  36.         log.info(job.getKey() + " will run at: " + runTime);  
  37.           
  38.         sched.start();  
  39.           
  40.         log.info("------- Started Scheduler -----------------");  
  41.         log.info("------- Waiting 65 seconds... -------------");  
  42.           
  43.         try {  
  44.             Thread.sleep(65L * 1000L);  
  45.         } catch (InterruptedException e) {  
  46.             e.printStackTrace();  
  47.         }  
  48.           
  49.         log.info("------- Shutting Down ---------------------");  
  50.         sched.shutdown(true);  
  51.         log.info("------- Shutdown Complete -----------------");  
  52.     }  
  53.       
  54.     public static void main(String[] args) throws Exception {  
  55.         SimpleExample example = new SimpleExample();  
  56.         example.run();  
  57.     }  
  58. }  


Example2 简单触发器

  1. public class SimpleJob implements Job {  
  2.     private static Logger _log = LoggerFactory.getLogger(SimpleJob.class);  
  3.   
  4.     public SimpleJob() {  
  5.     }  
  6.       
  7.     @Override  
  8.     public void execute(JobExecutionContext context)  
  9.             throws JobExecutionException {  
  10.         JobKey jobKey = context.getJobDetail().getKey();  
  11.         _log.info("SimpleJob says: " + jobKey + " executing at " + new Date());  
  12.     }  
  13. }  
  14.   
  15.   
  16. public class SimpleTriggerExample {  
  17.     public void run() throws Exception {  
  18.         Logger log = LoggerFactory.getLogger(SimpleTriggerExample.class);  
  19.   
  20.         log.info("------- Initializing -------------------");  
  21.   
  22.         // 得到调度器实例的引用  
  23.         SchedulerFactory sf = new StdSchedulerFactory();  
  24.         Scheduler sched = sf.getScheduler();  
  25.   
  26.         log.info("------- Initialization Complete --------");  
  27.         log.info("------- Scheduling Jobs ----------------");  
  28.   
  29.         // jobs can be scheduled before sched.start() has been called  
  30.   
  31.         // 任务开始时间的秒数是15的倍数  
  32.         Date startTime = DateBuilder.nextGivenSecondDate(null15);  
  33.   
  34.         // job1开始时间的秒数是15的倍数  
  35.         JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("job1""group1").build();  
  36.         SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()  
  37.                 .withIdentity("trigger1""group1").startAt(startTime).build();  
  38.         // 调度任务  
  39.         Date ft = sched.scheduleJob(job, trigger);  
  40.         log.info(job.getKey() + " will run at: " + ft + " and repeat: "  
  41.                 + trigger.getRepeatCount() + " times, every "  
  42.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  43.   
  44.         // job2开始时间的秒数是15的倍数  
  45.         job = JobBuilder.newJob(SimpleJob.class).withIdentity("job2""group1").build();  
  46.         trigger = (SimpleTrigger) TriggerBuilder.newTrigger().withIdentity(  
  47.                 "trigger2""group1").startAt(startTime).build();  
  48.         ft = sched.scheduleJob(job, trigger);  
  49.         log.info(job.getKey() + " will run at: " + ft + " and repeat: "  
  50.                 + trigger.getRepeatCount() + " times, every "  
  51.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  52.   
  53.         // job3开始时间的秒数是15的倍数(运行一次,重复10次,共11次,每次运行间隔为10s)  
  54.         job = JobBuilder.newJob(SimpleJob.class).withIdentity("job3""group1").build();  
  55.         trigger = TriggerBuilder.newTrigger()  
  56.                 .withIdentity("trigger3""group1").startAt(startTime)  
  57.                 .withSchedule(  
  58.                         SimpleScheduleBuilder.simpleSchedule()  
  59.                                 .withIntervalInSeconds(10).withRepeatCount(10))  
  60.                 .build();  
  61.         ft = sched.scheduleJob(job, trigger);  
  62.         log.info(job.getKey() + " will run at: " + ft + " and repeat: "  
  63.                 + trigger.getRepeatCount() + " times, every "  
  64.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  65.   
  66.           
  67.         // 相同的job3开始时间的秒数是15的倍数(运行一次,重复2次,共3次,每次运行间隔为10s)  
  68.         trigger = TriggerBuilder.newTrigger()  
  69.                 .withIdentity("trigger3""group2").startAt(startTime)  
  70.                 .withSchedule(  
  71.                         SimpleScheduleBuilder.simpleSchedule()  
  72.                                 .withIntervalInSeconds(10).withRepeatCount(2))  
  73.                 .forJob(job).build();  
  74.         ft = sched.scheduleJob(trigger);  
  75.         log.info(job.getKey() + " will [also] run at: " + ft + " and repeat: "  
  76.                 + trigger.getRepeatCount() + " times, every "  
  77.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  78.   
  79.         // job4开始时间的秒数是15的倍数(运行一次,重复5次,共6次,每次运行间隔为10s)  
  80.         job = JobBuilder.newJob(SimpleJob.class).withIdentity("job4""group1").build();  
  81.         trigger = TriggerBuilder.newTrigger().withIdentity("trigger4""group1").startAt(  
  82.                 startTime).withSchedule(  
  83.                         SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).withRepeatCount(5))  
  84.                 .build();  
  85.         ft = sched.scheduleJob(job, trigger);  
  86.         log.info(job.getKey() + " will run at: " + ft + " and repeat: "  
  87.                 + trigger.getRepeatCount() + " times, every "  
  88.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  89.   
  90.         // job5会立即调度,运行时间在5分钟后  
  91.         job = JobBuilder.newJob(SimpleJob.class).withIdentity("job5""group1").build();  
  92.         trigger = (SimpleTrigger) TriggerBuilder.newTrigger().withIdentity("trigger5",  
  93.                 "group1").startAt(DateBuilder.futureDate(5, IntervalUnit.MINUTE)).build();  
  94.         ft = sched.scheduleJob(job, trigger);  
  95.         log.info(job.getKey() + " will run at: " + ft + " and repeat: "  
  96.                 + trigger.getRepeatCount() + " times, every "  
  97.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  98.   
  99.         // job6开始时间的秒数是15的倍数,并且每40秒会重复运行一次,无限重复  
  100.         job = JobBuilder.newJob(SimpleJob.class).withIdentity("job6""group1").build();  
  101.         trigger = TriggerBuilder.newTrigger().withIdentity("trigger6""group1").startAt(  
  102.                 startTime).withSchedule(  
  103.                         SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever())  
  104.                 .build();  
  105.         ft = sched.scheduleJob(job, trigger);  
  106.         log.info(job.getKey() + " will run at: " + ft + " and repeat: "  
  107.                 + trigger.getRepeatCount() + " times, every "  
  108.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  109.   
  110.         log.info("------- Starting Scheduler ----------------");  
  111.   
  112.         // 所有的任务已加入调度器,但调度器未开始之前所有的任务都不会运行  
  113.         sched.start();  
  114.         log.info("------- Started Scheduler -----------------");  
  115.         // 调度器运行后任务仍然可以被调度  
  116.           
  117.         // job7开始时间的秒数是15的倍数,并且每5分钟会重复运行一次,重复20次  
  118.         job = JobBuilder.newJob(SimpleJob.class).withIdentity("job7""group1").build();  
  119.         trigger = TriggerBuilder.newTrigger().withIdentity("trigger7""group1").startAt(  
  120.                 startTime).withSchedule(  
  121.                         SimpleScheduleBuilder.simpleSchedule().withIntervalInMinutes(5).withRepeatCount(20))  
  122.                 .build();  
  123.         ft = sched.scheduleJob(job, trigger);  
  124.         log.info(job.getKey() + " will run at: " + ft + " and repeat: "  
  125.                 + trigger.getRepeatCount() + " times, every "  
  126.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  127.   
  128.         // job8可以直接运行,而不使用触发器  
  129.         job = JobBuilder.newJob(SimpleJob.class).withIdentity("job8""group1")  
  130.                 .storeDurably().build();  
  131.         sched.addJob(job, true);  
  132.         log.info("'Manually' triggering job8...");  
  133.         sched.triggerJob(JobKey.jobKey("job8""group1"));  
  134.   
  135.         log.info("------- Waiting 30 seconds... --------------");  
  136.   
  137.         try {  
  138.             Thread.sleep(30L * 1000L);  
  139.         } catch (Exception e) {  
  140.             e.printStackTrace();  
  141.         }  
  142.   
  143.         // job7可以重复调度,开始时间的秒数是15的倍数,并且每5分钟会重复运行一次,重复20次  
  144.         log.info("------- Rescheduling... --------------------");  
  145.         trigger = TriggerBuilder.newTrigger().withIdentity("trigger7""group1").startAt(  
  146.                 startTime).withSchedule(  
  147.                         SimpleScheduleBuilder.simpleSchedule().withIntervalInMinutes(5).withRepeatCount(20))  
  148.                 .build();  
  149.   
  150.         ft = sched.rescheduleJob(trigger.getKey(), trigger);  
  151.         log.info("job7 rescheduled to run at: " + ft);  
  152.   
  153.         log.info("------- Waiting five minutes... ------------");  
  154.         try {  
  155.             // 等待5分钟  
  156.             Thread.sleep(300L * 1000L);  
  157.         } catch (Exception e) {  
  158.             e.printStackTrace();  
  159.         }  
  160.   
  161.         log.info("------- Shutting Down ---------------------");  
  162.   
  163.         sched.shutdown(true);  
  164.   
  165.         log.info("------- Shutdown Complete -----------------");  
  166.   
  167.         // 显示调度器的状态  
  168.         SchedulerMetaData metaData = sched.getMetaData();  
  169.         log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");  
  170.     }  
  171.   
  172.     public static void main(String[] args) throws Exception {  
  173.         SimpleTriggerExample example = new SimpleTriggerExample();  
  174.         example.run();  
  175.     }  
  176. }  

Example 3 crontab格式的触发器

  1. public class SimpleJob implements Job {  
  2.   
  3.     private static Logger _log = LoggerFactory.getLogger(SimpleJob.class);  
  4.   
  5.     public SimpleJob() {  
  6.     }  
  7.   
  8.     public void execute(JobExecutionContext context)  
  9.             throws JobExecutionException {  
  10.         // 打印job的名称和运行时间  
  11.         JobKey jobKey = context.getJobDetail().getKey();  
  12.         _log.info("SimpleJob says: " + jobKey + " executing at " + new Date());  
  13.     }  
  14. }  
  15.   
  16.   
  17. public class CronTriggerExample {  
  18.   
  19.   public void run() throws Exception {  
  20.     Logger log = LoggerFactory.getLogger(CronTriggerExample.class);  
  21.   
  22.     log.info("------- Initializing -------------------");  
  23.   
  24.     // 得到调度器的引用  
  25.     SchedulerFactory sf = new StdSchedulerFactory();  
  26.     Scheduler sched = sf.getScheduler();  
  27.   
  28.     log.info("------- Initialization Complete --------");  
  29.   
  30.     log.info("------- Scheduling Jobs ----------------");  
  31.   
  32.     // job可以在调度器运行前被调度  
  33.   
  34.     // job 1 每20秒运行1次  
  35.     JobDetail job = newJob(SimpleJob.class).withIdentity("job1""group1").build();  
  36.     CronTrigger trigger = newTrigger().withIdentity("trigger1""group1").withSchedule(cronSchedule("0/20 * * * * ?"))  
  37.         .build();  
  38.     Date ft = sched.scheduleJob(job, trigger);  
  39.     log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "  
  40.              + trigger.getCronExpression());  
  41.   
  42.     // job 2 在偶数分钟的第15秒运行  
  43.     job = newJob(SimpleJob.class).withIdentity("job2""group1").build();  
  44.     trigger = newTrigger().withIdentity("trigger2""group1").withSchedule(cronSchedule("15 0/2 * * * ?")).build();  
  45.     ft = sched.scheduleJob(job, trigger);  
  46.     log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "  
  47.              + trigger.getCronExpression());  
  48.   
  49.     // job 3 在8-17点的偶数分钟运行  
  50.     job = newJob(SimpleJob.class).withIdentity("job3""group1").build();  
  51.     trigger = newTrigger().withIdentity("trigger3""group1").withSchedule(cronSchedule("0 0/2 8-17 * * ?")).build();  
  52.     ft = sched.scheduleJob(job, trigger);  
  53.     log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "  
  54.              + trigger.getCronExpression());  
  55.   
  56.     // job 4 在17-23点分钟是3的倍数运行  
  57.     job = newJob(SimpleJob.class).withIdentity("job4""group1").build();  
  58.     trigger = newTrigger().withIdentity("trigger4""group1").withSchedule(cronSchedule("0 0/3 17-23 * * ?")).build();  
  59.     ft = sched.scheduleJob(job, trigger);  
  60.     log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "  
  61.              + trigger.getCronExpression());  
  62.   
  63.     // job 5 在每月1号或15号的10点运行  
  64.     job = newJob(SimpleJob.class).withIdentity("job5""group1").build();  
  65.     trigger = newTrigger().withIdentity("trigger5""group1").withSchedule(cronSchedule("0 0 10am 1,15 * ?")).build();  
  66.     ft = sched.scheduleJob(job, trigger);  
  67.     log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "  
  68.              + trigger.getCronExpression());  
  69.   
  70.     // job 6 周一至周五的每30秒运行一次  
  71.     job = newJob(SimpleJob.class).withIdentity("job6""group1").build();  
  72.     trigger = newTrigger().withIdentity("trigger6""group1").withSchedule(cronSchedule("0,30 * * ? * MON-FRI"))  
  73.         .build();  
  74.     ft = sched.scheduleJob(job, trigger);  
  75.     log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "  
  76.              + trigger.getCronExpression());  
  77.   
  78.     // job 7 在周六、周日的每30秒运行一次  
  79.     job = newJob(SimpleJob.class).withIdentity("job7""group1").build();  
  80.     trigger = newTrigger().withIdentity("trigger7""group1").withSchedule(cronSchedule("0,30 * * ? * SAT,SUN"))  
  81.         .build();  
  82.     ft = sched.scheduleJob(job, trigger);  
  83.     log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "  
  84.              + trigger.getCronExpression());  
  85.   
  86.     log.info("------- Starting Scheduler ----------------");  
  87.   
  88.     // 调度器运行前所有任务不会运行  
  89.     sched.start();  
  90.   
  91.     log.info("------- Started Scheduler -----------------");  
  92.   
  93.     log.info("------- Waiting five minutes... ------------");  
  94.     try {  
  95.       Thread.sleep(300L * 1000L);  
  96.     } catch (Exception e) {  
  97.       e.printStackTrace();  
  98.     }  
  99.   
  100.     log.info("------- Shutting Down ---------------------");  
  101.   
  102.     sched.shutdown(true);  
  103.   
  104.     log.info("------- Shutdown Complete -----------------");  
  105.   
  106.     SchedulerMetaData metaData = sched.getMetaData();  
  107.     log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");  
  108.   
  109.   }  
  110.   
  111.   public static void main(String[] args) throws Exception {  
  112.   
  113.     CronTriggerExample example = new CronTriggerExample();  
  114.     example.run();  
  115.   }  
  116.   
  117. }  


Example4 向任务传递参数

  1. // 接收参数和维护状态的示例,注意这两个注解  
  2. @PersistJobDataAfterExecution   // 每次执行后会持久化JobData  
  3. @DisallowConcurrentExecution    // 不允许并发执行  
  4. public class ColorJob implements Job {  
  5.   
  6.     private static Logger _log = LoggerFactory.getLogger(ColorJob.class);  
  7.       
  8.     // 静态参数  
  9.     public static final String FAVORITE_COLOR = "favorite color";  
  10.     public static final String EXECUTION_COUNT = "count";  
  11.       
  12.     // 因为quartz每次执行任务时都会重新实例化一个类,所以非静态成员变量不能用来维护状态  
  13.     private int _counter = 1;  
  14.   
  15.     public ColorJob() {  
  16.     }  
  17.   
  18.     public void execute(JobExecutionContext context)  
  19.         throws JobExecutionException {  
  20.         // 获取jobkey类似group1.job1  
  21.         JobKey jobKey = context.getJobDetail().getKey();  
  22.           
  23.         // 获取并打印传递过来的参数  
  24.         JobDataMap data = context.getJobDetail().getJobDataMap();  
  25.         String favoriteColor = data.getString(FAVORITE_COLOR);  
  26.         int count = data.getInt(EXECUTION_COUNT);  
  27.         _log.info("ColorJob: " + jobKey + " executing at " + new Date() + "\n" +  
  28.             "  favorite color is " + favoriteColor + "\n" +   
  29.             "  execution count (from job map) is " + count + "\n" +   
  30.             "  execution count (from job member variable) is " + _counter);  
  31.           
  32.         // 增加count并保存到job的map中,所以job状态可以维护  
  33.         count++;  
  34.         data.put(EXECUTION_COUNT, count);  
  35.           
  36.         // 增加本地成员变量,通过成员变量不能维护job状态  
  37.         _counter++;  
  38.     }  
  39. }  
  40.   
  41.   
  42.   
  43. public class JobStateExample {  
  44.   
  45.     public void run() throws Exception {  
  46.         Logger log = LoggerFactory.getLogger(JobStateExample.class);  
  47.   
  48.         log.info("------- Initializing -------------------");  
  49.   
  50.         // 得到调度器的引用  
  51.         SchedulerFactory sf = new StdSchedulerFactory();  
  52.         Scheduler sched = sf.getScheduler();  
  53.   
  54.         log.info("------- Initialization Complete --------");  
  55.   
  56.         log.info("------- Scheduling Jobs ----------------");  
  57.   
  58.         // 开始时间秒数是10的倍数  
  59.         Date startTime = nextGivenSecondDate(null10);  
  60.   
  61.         // job1 会在秒数是10的倍数开始,重复4次,每10秒重复1次  
  62.         JobDetail job1 = newJob(ColorJob.class).withIdentity("job1""group1")  
  63.                 .build();  
  64.         SimpleTrigger trigger1 = newTrigger()  
  65.                 .withIdentity("trigger1""group1").startAt(startTime)  
  66.                 .withSchedule(  
  67.                         simpleSchedule().withIntervalInSeconds(10)  
  68.                                 .withRepeatCount(4)).build();  
  69.         // 向 job1 传递参数  
  70.         job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");  
  71.         job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);  
  72.         Date scheduleTime1 = sched.scheduleJob(job1, trigger1);  
  73.         log.info(job1.getKey() + " will run at: " + scheduleTime1  
  74.                 + " and repeat: " + trigger1.getRepeatCount()  
  75.                 + " times, every " + trigger1.getRepeatInterval() / 1000  
  76.                 + " seconds");  
  77.   
  78.         // job2 会在秒数是10的倍数开始,重复4次,每10秒重复1次  
  79.         JobDetail job2 = newJob(ColorJob.class).withIdentity("job2""group1")  
  80.                 .build();  
  81.         SimpleTrigger trigger2 = newTrigger()  
  82.                 .withIdentity("trigger2""group1").startAt(startTime)  
  83.                 .withSchedule(  
  84.                         simpleSchedule().withIntervalInSeconds(10)  
  85.                                 .withRepeatCount(4)).build();  
  86.         // 向 job2传递参数  
  87.         job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");  
  88.         job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);  
  89.         Date scheduleTime2 = sched.scheduleJob(job2, trigger2);  
  90.         log.info(job2.getKey().toString() + " will run at: " + scheduleTime2  
  91.                 + " and repeat: " + trigger2.getRepeatCount()  
  92.                 + " times, every " + trigger2.getRepeatInterval() / 1000  
  93.                 + " seconds");  
  94.   
  95.         log.info("------- Starting Scheduler ----------------");  
  96.   
  97.         // 所有的任务已加入调度器,但调度器未开始之前所有的任务都不会运行  
  98.         sched.start();  
  99.   
  100.         log.info("------- Started Scheduler -----------------");  
  101.   
  102.         log.info("------- Waiting 60 seconds... -------------");  
  103.         try {  
  104.             Thread.sleep(60L * 1000L);  
  105.         } catch (Exception e) {  
  106.             //  
  107.         }  
  108.   
  109.         log.info("------- Shutting Down ---------------------");  
  110.   
  111.         sched.shutdown(true);  
  112.   
  113.         log.info("------- Shutdown Complete -----------------");  
  114.   
  115.         SchedulerMetaData metaData = sched.getMetaData();  
  116.         log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");  
  117.   
  118.     }  
  119.   
  120.     public static void main(String[] args) throws Exception {  
  121.   
  122.         JobStateExample example = new JobStateExample();  
  123.         example.run();  
  124.     }  
  125.   
  126. }  


Example5 错失任务执行策略

  1. /** 
  2.  * 一个哑任务,用于单元测试 
  3.  */  
  4. @PersistJobDataAfterExecution  
  5. @DisallowConcurrentExecution  
  6. public class StatefulDumbJob implements Job {  
  7.     // 常量  
  8.     public static final String NUM_EXECUTIONS = "NumExecutions";  
  9.     public static final String EXECUTION_DELAY = "ExecutionDelay";  
  10.   
  11.     public StatefulDumbJob() {  
  12.     }  
  13.   
  14.     public void execute(JobExecutionContext context)  
  15.             throws JobExecutionException {  
  16.         System.err.println("---" + context.getJobDetail().getKey()  
  17.                 + " executing.[" + new Date() + "]");  
  18.   
  19.         // 取出job中的map中的数据,增加并重新放入job的map中  
  20.         JobDataMap map = context.getJobDetail().getJobDataMap();  
  21.         int executeCount = 0;  
  22.         if (map.containsKey(NUM_EXECUTIONS)) {  
  23.             executeCount = map.getInt(NUM_EXECUTIONS);  
  24.         }  
  25.         executeCount++;  
  26.         map.put(NUM_EXECUTIONS, executeCount);  
  27.   
  28.         // 如果包含延迟字段,则模拟任务延迟5秒  
  29.         long delay = 5000l;  
  30.         if (map.containsKey(EXECUTION_DELAY)) {  
  31.             delay = map.getLong(EXECUTION_DELAY);  
  32.         }  
  33.         try {  
  34.             Thread.sleep(delay);  
  35.         } catch (Exception ignore) {  
  36.         }  
  37.           
  38.         // 完成任务,打印完成语句  
  39.         System.err.println("  -" + context.getJobDetail().getKey()  
  40.                 + " complete (" + executeCount + ").");  
  41.     }  
  42. }  
  43.   
  44.   
  45.   
  46. public class MisfireExample {  
  47.   
  48.     public void run() throws Exception {  
  49.         Logger log = LoggerFactory.getLogger(MisfireExample.class);  
  50.   
  51.         log.info("------- Initializing -------------------");  
  52.         // 得到调度器的引用  
  53.         SchedulerFactory sf = new StdSchedulerFactory();  
  54.         Scheduler sched = sf.getScheduler();  
  55.   
  56.         log.info("------- Initialization Complete -----------");  
  57.         log.info("------- Scheduling Jobs -----------");  
  58.   
  59.         // 开始时间秒数是15的倍数  
  60.         Date startTime = nextGivenSecondDate(null15);  
  61.   
  62.         // 有状态job1每3秒运行1次,但会延迟10秒(任务中睡眠了10秒模拟了执行任务需要10秒)  
  63.         JobDetail job = newJob(StatefulDumbJob.class).withIdentity(  
  64.                 "statefulJob1""group1").usingJobData(  
  65.                 StatefulDumbJob.EXECUTION_DELAY, 10000L).build();  
  66.         SimpleTrigger trigger = newTrigger().withIdentity("trigger1""group1")  
  67.                 .startAt(startTime).withSchedule(  
  68.                         simpleSchedule().withIntervalInSeconds(3)  
  69.                                 .repeatForever()).build();  
  70.         Date ft = sched.scheduleJob(job, trigger);  
  71.         log.info(job.getKey() + " will run at: " + ft + " and repeat: "  
  72.                 + trigger.getRepeatCount() + " times, every "  
  73.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  74.   
  75.         // 有状态job2每3秒运行1次,但会延迟10秒(任务中睡眠了10秒模拟了执行任务需要10秒)  
  76.         // job2设置了策略,所以错失后会立即触发,而不会等到下一个触发点  
  77.         job = newJob(StatefulDumbJob.class).withIdentity("statefulJob2",  
  78.                 "group1").usingJobData(StatefulDumbJob.EXECUTION_DELAY, 10000L)  
  79.                 .build();  
  80.         trigger = newTrigger().withIdentity("trigger2""group1").startAt(  
  81.                 startTime).withSchedule(  
  82.                 simpleSchedule().withIntervalInSeconds(3).repeatForever()  
  83.                 // 设置错失触发后的调度策略  
  84.                         .withMisfireHandlingInstructionNowWithExistingCount())  
  85.                 .build();  
  86.         ft = sched.scheduleJob(job, trigger);  
  87.         log.info(job.getKey() + " will run at: " + ft + " and repeat: "  
  88.                 + trigger.getRepeatCount() + " times, every "  
  89.                 + trigger.getRepeatInterval() / 1000 + " seconds");  
  90.   
  91.         log.info("------- Starting Scheduler ----------------");  
  92.         sched.start();  
  93.         log.info("------- Started Scheduler -----------------");  
  94.   
  95.         try {  
  96.             Thread.sleep(600L * 1000L);  
  97.         } catch (Exception e) {  
  98.         }  
  99.   
  100.         log.info("------- Shutting Down ---------------------");  
  101.         sched.shutdown(true);  
  102.         log.info("------- Shutdown Complete -----------------");  
  103.   
  104.         SchedulerMetaData metaData = sched.getMetaData();  
  105.         log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");  
  106.     }  
  107.   
  108.     public static void main(String[] args) throws Exception {  
  109.         MisfireExample example = new MisfireExample();  
  110.         example.run();  
  111.     }  
  112.   
  113.     //本范例中,触发的间隔被设置为3秒,但是由于任务体执行间睡眠10秒,导致了错失触发的产生。  
  114.     //实际运行的效果,2个任务执行的间隔为10秒。  
  115.     //由于丢失触发时,job2的策略是立即触发,而job1是等待下一次机会触发。所以job2会赶在job1的前头,最终运行次数大于job1。  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值