Spring整合Quartz


1.定时执行的类

  1. package thb.quartz; 
  2.  
  3. public class QuartzJob { 
  4.      
  5.     /** 
  6.      * 定时执行的方法 
  7.      */ 
  8.     public void work() { 
  9.         System.out.println(System.currentTimeMillis() + ">>>执行定时任务。。。"); 
  10.     } 
  11.  

2.quartz配置文件

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  3.     xmlns:util="http://www.springframework.org/schema/util" 
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd" 
  5.     default-lazy-init="true"
  6.      
  7.     <!-- 要调用执行定时任务的类 --> 
  8.     <bean id="quartzJob" class="thb.quartz.QuartzJob"></bean> 
  9.      
  10.     <!-- 定义调用对象和调用对象的方法(触发器) --> 
  11.     <bean id="jobTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"
  12.         <!-- 调用的类 --> 
  13.         <property name="targetObject"
  14.             <ref bean="quartzJob"/> 
  15.         </property> 
  16.         <!-- 调用的方法 --> 
  17.         <property name="targetMethod"
  18.             <value>work</value> 
  19.         </property> 
  20.     </bean> 
  21.      
  22.     <!-- 定义触发事件(调度器) --> 
  23.     <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean"
  24.         <property name="jobDetail" ref="jobTask"></property> 
  25.         <!-- 10点开始,每隔1分钟 --> 
  26.         <property name="cronExpression" value="0 * 10 * * ?"></property> 
  27.     </bean> 
  28.      
  29.     <bean id="startQuartz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
  30.         <property name="triggers"
  31.             <list> 
  32.                 <ref bean="doTime"/> 
  33.             </list> 
  34.         </property> 
  35.     </bean> 
  36. </beans> 

3.测试代码

  1. package thb.quartz; 
  2.  
  3. import org.springframework.context.ApplicationContext; 
  4. import org.springframework.context.support.FileSystemXmlApplicationContext; 
  5.  
  6. public class QuartzTest { 
  7.  
  8.     /** 
  9.      * 定时任务测试 
  10.      */ 
  11.     public static void main(String[] args) { 
  12.         ApplicationContext ctx = new FileSystemXmlApplicationContext("/resource/spring/quartz.xml"); 
  13.         System.out.println("定时任务开始执行。。。"); 
  14.     } 
  15.  

相关内容