java2借助于java.util.Timer和java.util.TimerTask,这样两个类能够为应用提供简单定时器功能。
而Quartz是Open Source社区努力的结果,它能够提供任务调度服务,任何J2SE和J2EE应用都能够使用它,借助于Quartz,开发者能够完成各种复杂的任务调度。
Spring集成了上述两种任务调度服务的支持。
下面对Quartz的使用进行介绍:
创建一个java类:
package com.openv.spring; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; public class LogJobBean extends QuartzJobBean{ protected static final Log log=LogFactory.getLog(LogJobBean.class); private int timeout; public void setTimeout(int timeout){ log.info("setTimeout()........."); this.timeout=timeout; } @Override protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException { log.info("Creating LogJobBean()........."); } }
写入配置文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean name="logJob" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass"> <value>com.openv.spring.LogJobBean</value> </property> <property name="jobDataAsMap"> <map> <entry key="timeout"> <value>10</value> </entry> </map> </property> </bean> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail"> <ref bean="logJob"/> </property> <property name="startDelay"> <value>5000</value> </property> <property name="repeatInterval"> <value>2000</value> </property> <property name="repeatCount"> <value>3</value> </property> </bean> <bean id="sfb" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref local="simpleTrigger"/> </list> </property> </bean> </beans>
使用测试类:
package com.openv.spring; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; /** * * @author weiliuhong * */ public class Main { protected static Log log=LogFactory.getLog(Main.class); /** * @param <Scheduler> * @param args */ public static void main(String[] args) { Resource resource=new ClassPathResource("appcontext.xml"); BeanFactory factory=new XmlBeanFactory(resource); Scheduler sfb=(Scheduler)factory.getBean("sfb"); try{ Thread.sleep(20000); }catch (InterruptedException e) { log.error(e.getMessage(),e); } try{ sfb.shutdown(); }catch(SchedulerException se){ log.error(se.getMessage(),se); } } }
这样就实现对timer的调用