定时器quartz的应用

用quartz可以实现web或非web模式的定时器

1、配置文件

quartz_job.xml
  1. xml version="1.0" encoding="UTF-8"?>  
  2. <quartz xmlns="http://www.opensymphony.com/quartz/JobSchedulingData"  
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.         overwrite-existing-jobs="true">  
  5.        
  6.     <job>  
  7.         <job-detail>  
  8.             <name>yayaittname>  
  9.             <group>CRAWLER_JOB_GROUPgroup>  
  10.   
  11.             <description>send task per daydescription>  
  12.             <job-class>com.yahaitt.quartz.QuartzSystemjob-class>  
  13.   
  14.             <job-data-map allows-transient-data="true">  
  15.                <entry>  
  16.                     <key>usernamekey>  
  17.                     <value>wujinlivalue>  
  18.                 entry>  
  19.                 <entry>  
  20.                     <key>passwordkey>  
  21.                     <value>mahaibovalue>  
  22.   
  23.                 entry>  
  24.             job-data-map>  
  25.         job-detail>  
  26.         <trigger>  
  27.             <cron>  
  28.                 <name>hourTaskJob-triggername>  
  29.                 <group>CRAWLER_TRIGGER_GROUPgroup>  
  30.                 <job-name>yayaittjob-name>  
  31.                 <job-group>CRAWLER_JOB_GROUPjob-group>  
  32.   
  33.   
  34.                 <cron-expression>1/12 * * * * ?cron-expression>  
  35.   
  36.             cron>  
  37.         trigger>  
  38.     job>  
  39.   
  40.        
  41.        
  42.        
  43.      
  44. quartz>  

该定时器实现了每12秒触发类com.yahaitt.quartz.QuartzSystem的execute函数,并通过java-data-map标签来实现参数的传递,如果不需要传递参数,可以将整个java-data-map标签去除。

需要注意的是job-detail与trigger中各子标签间的关系,比如trigger中job-name和job-group要与job-detail中的name和group对应。

可以通过在quartz标签中添加多个job来实现多个定时器的管理。

2、定义org.quartz.Job接口的实现类

QuartzSystem.java
  1. package com.yahaitt.quartz;   
  2.   
  3. import org.quartz.Job;   
  4. import org.quartz.JobExecutionContext;   
  5. import org.quartz.JobExecutionException;   
  6.   
  7. public class QuartzSystem implements Job {   
  8.   
  9.     public void execute(JobExecutionContext context) throws JobExecutionException {   
  10.         // TODO Auto-generated method stub   
  11.            
  12.         String username = context.getJobDetail().getJobDataMap().getString("username");   
  13.         String password = context.getJobDetail().getJobDataMap().getString("password");   
  14.         System.out.println("username:" + username);   
  15.         System.out.println("password:" + password);   
  16.     }   
  17.   
  18. }   

通过调用JobExecutionContext 的getJobDetail().getJobDataMap().getString(String paramname)来取得配置文件中定义的参数的值。

当定时器触发时,将执行该类的execute函数。

3、设置监听器

TaskScheduler.java
  1. package com.yahaitt.quartz;   
  2.   
  3. import java.util.Properties;   
  4.   
  5. import org.apache.log4j.Logger;   
  6. import org.quartz.Scheduler;   
  7. import org.quartz.SchedulerException;   
  8. import org.quartz.SchedulerFactory;   
  9. import org.quartz.impl.StdSchedulerFactory;   
  10. import org.quartz.xml.JobSchedulingDataProcessor;   
  11.   
  12.   
  13. public class TaskScheduler {   
  14.     // Logger   
  15.     private static Logger logger = Logger.getLogger(TaskScheduler.class);   
  16.        
  17.     private static Scheduler scheduler;   
  18.        
  19.     private String jobsConfigFile = "quartz-jobs.xml";   
  20.        
  21.     public TaskScheduler() {   
  22.         initScheduler();   
  23.     }   
  24.        
  25.     /**  
  26.      *   
  27.      * @param fileName  
  28.      * @return  
  29.      */  
  30.     public void initScheduler() {   
  31.         try {   
  32.             StdSchedulerFactory factory = new StdSchedulerFactory();   
  33.             //   
  34.             Properties properties = new Properties();   
  35.             properties.put("org.quartz.scheduler.instanceName","DefaultQuartzScheduler");   
  36.             properties.put("org.quartz.scheduler.rmi.export","false");   
  37.             properties.put("org.quartz.scheduler.rmi.proxy","false");   
  38.             properties.put("org.quartz.scheduler.wrapJobExecutionInUserTransaction","false");   
  39.             properties.put("org.quartz.threadPool.class","org.quartz.simpl.SimpleThreadPool");   
  40.             properties.put("org.quartz.threadPool.threadCount","20");   
  41.             properties.put("org.quartz.threadPool.threadPriority","5");   
  42.             properties.put("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread","true");   
  43.             properties.put("org.quartz.jobStore.misfireThreshold","60000");   
  44.             properties.put("org.quartz.jobStore.class","org.quartz.simpl.RAMJobStore");   
  45. //          org.quartz.plugin.jobInitializer.validating = false   
  46. //          org.quartz.plugin.jobInitializer.validatingSchema = false   
  47. //          org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin   
  48. //          org.quartz.plugin.jobInitializer.fileName = quartz-jobs.xml   
  49. //          org.quartz.plugin.jobInitializer.overWriteExistingJobs = false   
  50. //          org.quartz.plugin.jobInitializer.failOnFileNotFound = true    
  51.             factory.initialize(properties);   
  52.             SchedulerFactory sf = (StdSchedulerFactory)factory;   
  53.             scheduler = sf.getScheduler();   
  54.             //Placing a Scheduler in Stand-by Mode   
  55.             //scheduler.standby();   
  56.         } catch (SchedulerException e) {   
  57.             e.printStackTrace();   
  58.             logger.error(e);   
  59.         }   
  60.     }   
  61.        
  62.     /**  
  63.      * 从指定的任务配置文件中初始化计划任务  
  64.      * @param jobsConfig  
  65.      * @throws Exception  
  66.      */  
  67.     public void initJobs(String jobsConfig) throws Exception {   
  68.         //   
  69.         this.jobsConfigFile = jobsConfig;   
  70.         //   
  71.         JobSchedulingDataProcessor xmlProcessor = new JobSchedulingDataProcessor();   
  72.         //the last parameter here (the boolean one)is for overwriting existing jobs   
  73.         xmlProcessor.processFileAndScheduleJobs(jobsConfigFile, scheduler, true);   
  74.     }   
  75.        
  76.     /**  
  77.      * 开启计划任务  
  78.      * @throws SchedulerException  
  79.      */  
  80.     public void startScheduler() throws SchedulerException {   
  81.         //   Scheduler will not execute jobs until it has been started (though they can be scheduled before start())    
  82.         scheduler.start();   
  83.     }   
  84.        
  85.     /**  
  86.      * 停止计划任务  
  87.      * @throws SchedulerException  
  88.      */  
  89.     public void shutdownScheduler() throws SchedulerException {   
  90.         scheduler.shutdown();   
  91.     }   
  92.        
  93.     /**  
  94.      * @param args  
  95.      */  
  96.     public static void main(String[] args) {   
  97.         String jobsConfigfile = "E:/workspace/crawler/conf/quartz_job.xml";   
  98.         TaskScheduler scheduler = new TaskScheduler();   
  99.         try {   
  100.             scheduler.initJobs(jobsConfigfile);   
  101.             scheduler.startScheduler();   
  102.         } catch (Exception e) {   
  103.             e.printStackTrace();   
  104.         }   
  105.   
  106.     }   
  107.   
  108. }   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值