Quartz集成spring开发大全

一.固定xml调用quartz

准备工作:

1.导入quartz-1.x.x.x.jar到lib,可能还需要lib/sh4j-api-1.x.x.jar,log4g,sh4j.api,1,x,x,jar,sh4j.nop,1,x,x,jar

2.在src目录下创建quartz.properties(压缩quartz-1.x.x.x.jar 下的org/quarz下可得)

[html]  view plain copy
  1. # 配置主调度器属性  
  2. org.quartz.scheduler.instanceName = DefaultQuartzScheduler  
  3. org.quartz.scheduler.rmi.export = false  
  4. org.quartz.scheduler.rmi.proxy = false  
  5. org.quartz.scheduler.wrapJobExecutionInUserTransaction = false  
  6. # 配置线程池  
  7. # Quartz线程池的实现类  
  8. org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool  
  9. # 线程池的线程数量  
  10. org.quartz.threadPool.threadCount = 10  
  11. # 线程池里线程的优先级  
  12. org.quartz.threadPool.threadPriority = 5  
  13. org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true  
  14. # 配置作业存储  
  15. org.quartz.jobStore.misfireThreshold = 60000  
  16.   
  17. org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore  
  18.   
  19. #org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX  
  20. #org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.HSQLDBDelegate  
  21. #org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate  
  22. #org.quartz.jobStore.useProperties = true  
  23. #org.quartz.jobStore.tablePrefix = QRTZ_    
  24. #org.quartz.jobStore.isClustered = false    
  25. #org.quartz.jobStore.maxMisfiresToHandleAtATime=1   

 

3.编写触发时要执行的类

[java]  view plain copy
  1. package com.quartz;  
  2.   
  3. import org.quartz.JobExecutionContext;  
  4. import org.quartz.JobExecutionException;  
  5. import org.quartz.Trigger;  
  6. import org.springframework.scheduling.quartz.QuartzJobBean;  
  7.   
  8. public class TestQuartzJob extends QuartzJobBean{  
  9.   
  10.     @Override  
  11.     protected void executeInternal(JobExecutionContext jobexecutioncontext) throws JobExecutionException {  
  12.         // TODO Auto-generated method stub  
  13.         Trigger trigger = jobexecutioncontext.getTrigger();  
  14.         String triggerName = trigger.getName();       
  15.         System.out.println("MyQuartzJobBean"+triggerName);  
  16.     }  
  17.   
  18. }  


4.配置sping管理的配置文件quartzContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    http://www.springframework.org/schema/jee
    http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
<!-- 自定义工作类 -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<value>com.quartz.TestQuartzJob</value>
</property>
<property name="jobDataAsMap">
<map>
<!--
<entry key="upVersionDevService"> <ref bean="upVersionDevService"
/> </entry>
-->
</map>
</property>
</bean>
<!-- 注入的service的工作类 -->
<bean id="methodInvokingJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">         
<!-- 指定定时任务调度类 -->  
<property name="targetObject">
<ref bean="userService" />
</property>          
<!-- 指定定时任务调度方法 -->
<property name="targetMethod">
<value>save</value>  
</property>
</bean>

<!-- 每隔10秒自动调用 配置模板 使用复杂的cronTrigger-->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> 
<property name="jobDetail" ref="jobDetail" /> 
<property name="cronExpression" value="0/10 * * ? * * *" /> 
</bean> 
<bean  id="schedulerTrigger" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
<property name="triggers"> 
<list> 
<ref bean="cronTrigger"/>      
</list> 
</property> 
</bean>
        <!-- 延迟1秒后,每隔10秒自动调用 配置模板 使用简单的SimpleTriggerBean-->
<bean id="st01SimpleTrigger"   class="org.springframework.scheduling.quartz.SimpleTriggerBean">  
            <property name="jobDetail" ref="checkSt01Job"></property>  
            <property name="startDelay" value="1000"></property>  
           <property name="repeatInterval" value="10000"></property>  
    </bean>  
         
</beans>

[javascript]  view plain copy
  1.   

[javascript]  view plain copy
  1. cronTrigger表达式含义:  
  2. <property name="cronExpression" value="0/10 * * ? * * *" />  
  3.  <!--  0 0 0 1 * ?     
  4.   #       1.秒(0-59)  
  5.   #       2.分钟(0-59)   
  6.   #       3.小时(0-23)    
  7.   #       4.月份中的日期(1-31)    
  8.   #       5.月份(1-12或SUN-DEC)    
  9.   #       6.星期中的日期(1-7或SUN-SAT)    
  10.   #       7.年份(1970-2099)  
  11.     表达式意义  
  12.     "0 0 12 * * ?" 每天中午12点触发  
  13.     "0 15 10 ? * *" 每天上午10:15触发  
  14.     "0 15 10 * * ?" 每天上午10:15触发  
  15.     "0 15 10 * * ? *" 每天上午10:15触发  
  16.     "0 15 10 * * ? 2005" 2005年的每天上午10:15触发  
  17.     "0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发  
  18.     "0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发  
  19.     "0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发  
  20.     "0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发  
  21.     "0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发  
  22.     "0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发  
  23.     "0 15 10 15 * ?" 每月15日上午10:15触发  
  24.     "0 15 10 L * ?" 每月最后一日的上午10:15触发  
  25.     "0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发  
  26.     "0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发  
  27.     "0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发  
  28.     每天早上6点  
  29.     0 6 * * *  
  30.     每两个小时  
  31.     0 */2 * * *  
  32.     晚上11点到早上8点之间每两个小时,早上八点  
  33.     0 23-7/2,8 * * *  
  34.     每个月的4号和每个礼拜的礼拜一到礼拜三的早上11点  
  35.     0 11 4 * 1-3  
  36.     1月1日早上4点  
  37.     0 4 1 1 *  


[html]  view plain copy
  1.   

二程序动态调用quartz(动态设置job和定时器)

1.导入quartz-1.x.x.x.jar到lib,可能还需要lib/sh4j-api-1.x.x.jar,log4g,sh4j.api,1,x,x,jar,sh4j.nop,1,x,x,jar

2.在src目录下创建quartz.properties(压缩quartz-1.x.x.x.jar 下的org/quarz下可得)

3.配置sping管理的配置文件quartzContext.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  4.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:jee="http://www.springframework.org/schema/jee"  
  6.     xsi:schemaLocation="  
  7.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  8.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  9.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  
  10.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  11.     http://www.springframework.org/schema/jee  
  12.     <a target="_blank" href="http://www.springframework.org/schema/jee/spring-jee-2.5.xsd'>">http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"></a>  
[html]  view plain copy
  1. <u><span style="color:#0000ff"><!--要注入的包名--></span></u>  
[html]  view plain copy
  1. <context:component-scan base-package="com"/>  
  2.          <u><span style="color:#0000ff"><!--要注入的时间触发器--></span></u>  
[html]  view plain copy
  1. <bean name="quartzScheduler"  
  2.     class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  3.     <property name="applicationContextSchedulerContextKey" value="applicationContextKey" />  
  4.     <property name="configLocation" value="classpath:quartz.properties" />  
  5. </bean>  


 

4.spring中导入QuartzServiceImpl和IQuartzService2个类  作用是动态时间执行

[java]  view plain copy
  1. package com.quartz;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.quartz.CronExpression;  
  6.   
  7. public interface IQuartzService {  
  8.     /** 
  9.      * 根据 Quartz Cron Expression 调试任务 
  10.      * @param cronExpression  Quartz Cron 表达式,如 "0/10 * * ? * * *"等 
  11.      */  
  12.     void schedule(String cronExpression);  
  13.       
  14.     /** 
  15.      * 根据 Quartz Cron Expression 调试任务 
  16.      * @param name  Quartz CronTrigger名称 
  17.      * @param cronExpression Quartz Cron 表达式,如 "0/10 * * ? * * *"等 
  18.      */  
  19.     void schedule(String name,String cronExpression);  
  20.       
  21.     /** 
  22.      * 根据 Quartz Cron Expression 调试任务 
  23.      * @param cronExpression Quartz CronExpression 
  24.      */  
  25.     void schedule(CronExpression cronExpression);  
  26.       
  27.     /** 
  28.      * 根据 Quartz Cron Expression 调试任务 
  29.      * @param name Quartz CronTrigger名称 
  30.      * @param cronExpression Quartz CronExpression 
  31.      */  
  32.     void schedule(String name,CronExpression cronExpression);  
  33.       
  34.     /** 
  35.      * 在startTime时执行调试一次 
  36.      * @param startTime 调度开始时间 
  37.      */  
  38.     void schedule(Date startTime);    
  39.       
  40.     /** 
  41.      * 在startTime时执行调试一次 
  42.      * @param name Quartz SimpleTrigger 名称 
  43.      * @param startTime 调度开始时间 
  44.      */  
  45.     void schedule(String name,Date startTime);  
  46.       
  47.     /** 
  48.      * 在startTime时执行调试,endTime结束执行调度 
  49.      * @param startTime 调度开始时间 
  50.      * @param endTime 调度结束时间 
  51.      */  
  52.     void schedule(Date startTime,Date endTime);   
  53.       
  54.     /** 
  55.      * 在startTime时执行调试,endTime结束执行调度 
  56.      * @param name Quartz SimpleTrigger 名称 
  57.      * @param startTime 调度开始时间 
  58.      * @param endTime 调度结束时间 
  59.      */  
  60.     void schedule(String name,Date startTime,Date endTime);  
  61.       
  62.     /** 
  63.      * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次 
  64.      * @param startTime 调度开始时间 
  65.      * @param endTime 调度结束时间 
  66.      * @param repeatCount 重复执行次数 
  67.      */  
  68.     void schedule(Date startTime,Date endTime,int repeatCount);   
  69.       
  70.     /** 
  71.      * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次 
  72.      * @param name Quartz SimpleTrigger 名称 
  73.      * @param startTime 调度开始时间 
  74.      * @param endTime 调度结束时间 
  75.      * @param repeatCount 重复执行次数 
  76.      */  
  77.     void schedule(String name,Date startTime,Date endTime,int repeatCount);  
  78.       
  79.     /** 
  80.      * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次,每隔repeatInterval秒执行一次 
  81.      * @param startTime 调度开始时间 
  82.      * @param endTime 调度结束时间 
  83.      * @param repeatCount 重复执行次数 
  84.      * @param repeatInterval 执行时间隔间 
  85.      */  
  86.     void schedule(Date startTime,Date endTime,int repeatCount,long repeatInterval) ;  
  87.       
  88.     /** 
  89.      * 在startTime时执行调试,endTime结束执行调度,重复执行repeatCount次,每隔repeatInterval秒执行一次 
  90.      * @param name Quartz SimpleTrigger 名称 
  91.      * @param startTime 调度开始时间 
  92.      * @param endTime 调度结束时间 
  93.      * @param repeatCount 重复执行次数 
  94.      * @param repeatInterval 执行时间隔间 
  95.      */  
  96.     void schedule(String name,Date startTime,Date endTime,int repeatCount,long repeatInterval);  
  97.       
  98.     /** 
  99.      * 移除定时任务 
  100.      * @param name Quartz SimpleTrigger 名称 
  101.      */  
  102.     void removeSchedule(String name);  
  103. }  


 

[java]  view plain copy
  1. package com.quartz;  
  2.   
  3. import java.text.ParseException;  
  4. import java.util.Date;  
  5. import java.util.UUID;  
  6.   
  7. import org.quartz.CronExpression;  
  8. import org.quartz.CronTrigger;  
  9. import org.quartz.JobDetail;  
  10. import org.quartz.Scheduler;  
  11. import org.quartz.SchedulerException;  
  12. import org.quartz.SimpleTrigger;  
  13. import org.springframework.beans.factory.annotation.Autowired;  
  14. import org.springframework.beans.factory.annotation.Qualifier;  
  15. import org.springframework.stereotype.Service;  
  16.   
  17. @Service("schedulerService")  
  18. public class QuartzServiceImpl implements IQuartzService {  
  19.   
  20.     private Scheduler scheduler;  
  21.     private JobDetail jobDetail;  
  22.   
  23.     @Autowired  
  24.     public void setJobDetail(@Qualifier("jobDetail") JobDetail jobDetail) {  
  25.         this.jobDetail = jobDetail;  
  26.     }  
  27.   
  28.     @Autowired  
  29.     public void setScheduler(@Qualifier("quartzScheduler") Scheduler scheduler) {  
  30.         this.scheduler = scheduler;  
  31.     }  
  32.   
  33.     @Override  
  34.     public void schedule(String cronExpression) {  
  35.         schedule(null, cronExpression);  
  36.     }  
  37.   
  38.     @Override  
  39.     public void schedule(String name, String cronExpression) {  
  40.         try {  
  41.             schedule(name, new CronExpression(cronExpression));  
  42.         } catch (ParseException e) {  
  43.             throw new RuntimeException(e);  
  44.         }  
  45.     }  
  46.   
  47.     @Override  
  48.     public void schedule(CronExpression cronExpression) {  
  49.         schedule(null, cronExpression);  
  50.     }  
  51.   
  52.     @Override  
  53.     public void schedule(String name, CronExpression cronExpression) {  
  54.         if (name == null || name.trim().equals("")) {  
  55.             name = UUID.randomUUID().toString();  
  56.         }  
  57.   
  58.         try {  
  59.             scheduler.addJob(jobDetail, true);  
  60.   
  61.             CronTrigger cronTrigger = new CronTrigger(name, Scheduler.DEFAULT_GROUP, jobDetail.getName(),  
  62.                     Scheduler.DEFAULT_GROUP);  
  63.             cronTrigger.setCronExpression(cronExpression);  
  64.             scheduler.scheduleJob(cronTrigger);  
  65.             scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, cronTrigger);  
  66.         } catch (SchedulerException e) {  
  67.             throw new RuntimeException(e);  
  68.         }  
  69.     }  
  70.   
  71.     @Override  
  72.     public void schedule(Date startTime) {  
  73.         schedule(startTime, null);  
  74.     }  
  75.   
  76.     @Override  
  77.     public void schedule(String name, Date startTime) {  
  78.         schedule(name, startTime, null);  
  79.     }  
  80.   
  81.     @Override  
  82.     public void schedule(Date startTime, Date endTime) {  
  83.         schedule(startTime, endTime, 0);  
  84.     }  
  85.   
  86.     @Override  
  87.     public void schedule(String name, Date startTime, Date endTime) {  
  88.         schedule(name, startTime, endTime, 0);  
  89.     }  
  90.   
  91.     @Override  
  92.     public void schedule(Date startTime, Date endTime, int repeatCount) {  
  93.         schedule(null, startTime, endTime, 0);  
  94.     }  
  95.   
  96.     @Override  
  97.     public void schedule(String name, Date startTime, Date endTime, int repeatCount) {  
  98.         schedule(name, startTime, endTime, 0, 0L);  
  99.     }  
  100.   
  101.     @Override  
  102.     public void schedule(Date startTime, Date endTime, int repeatCount, long repeatInterval) {  
  103.         schedule(null, startTime, endTime, repeatCount, repeatInterval);  
  104.     }  
  105.   
  106.     @Override  
[java]  view plain copy
  1.        <span style="color:#ff0000">//根据传入时间触发注入的jobDetail  
  2. span>   public void schedule(String name, Date startTime, Date endTime, int repeatCount, long repeatInterval) {  
  3. if (name == null || name.trim().equals("")) {  
  4.     name = UUID.randomUUID().toString();  
  5. }  
  6.   
  7. try {  
  8.     scheduler.addJob(<span style="color:#ff0000">jobDetail</span>, true);  
  9.     System.out.println("startTime="+startTime);  
  10.     SimpleTrigger SimpleTrigger = new SimpleTrigger(name, Scheduler.DEFAULT_GROUP, jobDetail.getName(),  
  11.             Scheduler.DEFAULT_GROUP, startTime, endTime, repeatCount, repeatInterval);  
  12.     SimpleTrigger.getJobDaaMap().put('传入参数key','传入参数值'); <span style="color:#ff0000">//启动计划任务时可以调用此处传入的参数</span>  
[java]  view plain copy
  1.         scheduler.scheduleJob(SimpleTrigger);  
  2.         scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, SimpleTrigger);  
  3.   
  4.     } catch (SchedulerException e) {  
  5.         throw new RuntimeException(e);  
  6.     }  
  7. }  
  8.   
  9. @Override  
  10. <span style="color:#ff6600">//删除暂停计划</span>  
[java]  view plain copy
  1. public void removeSchedule(String name) {  
  2.     // TODO Auto-generated method stub  
  3.     try {  
  4.         scheduler.pauseTrigger(name,Scheduler.DEFAULT_GROUP);//ֹͣ������  
  5.         scheduler.unscheduleJob(name,Scheduler.DEFAULT_GROUP);//�Ƴ���  
  6.         scheduler.deleteJob(name,Scheduler.DEFAULT_GROUP);//ɾ������  
  7.     } catch (SchedulerException e) {  
  8.         // TODO Auto-generated catch block  
  9.         e.printStackTrace();  
  10.     }  
  11. }  
  12.   
  13. 在xml中注入  
[java]  view plain copy
  1.  <bean name="quartzService" class="com.quartz.QuartzServiceImpl" />  
[java]  view plain copy
  1.    

5.如何调用

     ApplicationContext springContext = new ClassPathXmlApplicationContext(new String[]{"classpath:com/springResource/*.xml"});
     QuartzServiceImpl quartzService = (QuartzServiceImpl)springContext.getBean("quartzService");  

      quartzService.setJobDetail(jobDetail);                  //动态设置任务

     quartzService.schedule("name=testQuartz2",DateUtil.parse("2012-12-12 23:42:00"));         //动态设置定时器时间

 

6设置不并发执行 <property name="concurrent" value="false"/>  

 

  1.    <bean id="demoJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" depends-on="demoService">  
  2.         <property name="targetObject" ref="demoService"/>  
  3.         <property name="targetMethod" value="demoQuartz">  
  4.           
  5.         </property>  
  6.         <property name="concurrent" value="false"/>  
  7.     </bean>  

 


三.最简单的方法,动态设置定时器

首先我们观察xml配置
    <bean id="backupDatabaseTrigger" class=" org.springframework.scheduling.quartz.CronTriggerBean">
        <property name=" jobDetail">
             <!-- 要执行的bean --> 
<ref bean="backupDatabaseJobDetail"/>
        </property>
         <!-- cron表达式 --> 
        <property name=" cronExpression">
            <!-- 每隔90分钟执行一次-->
            <value>0 0/90 * * * ?</value>
        </property>
    </bean> 
 
得出结论
        1个定时任务,需要 CronTriggerBean类和 jobDetail   cronExpression参数

那么我们就可以这样做了
    <bean id="backupDatabaseTrigger" class=" com.MyCronTriggerBean">
        <property name=" jobDetail">
             <!-- 要执行的bean --> 
<ref bean="backupDatabaseJobDetail"/>
        </property>
    </bean> 

MyCronTriggerBean extends CronTriggerBean{
setCronExpression                  //cronExpression你就可以动态设置了撒
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值