spring Quartz用法

第一步:DailyTask.java

package com.springinaction.quartz; import org.springframework.scheduling.quartz.QuartzJobBean; public class DailyTask extends QuartzJobBean { private HelloWorld helloWorld; public HelloWorld getHelloWorld() { return helloWorld; } public void setHelloWorld(HelloWorld helloWorld) { this.helloWorld = helloWorld; } protected void executeInternal(org.quartz.JobExecutionContext context) throws org.quartz.JobExecutionException { this.helloWorld.sayHello(); } }

第二步:HelloWorld.java

 

package com.springinaction.quartz; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class HelloWorld { public void sayHello() { Date now = Calendar.getInstance().getTime(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println("Hello World! " + simpleDateFormat.format(now)); } }

第三步:Spring的配置文件springquartz.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <bean id="helloWorld" class="com.springinaction.quartz.HelloWorld" /> <bean id="dailyRantEmailJob" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass" value="com.springinaction.quartz.DailyTask"></property> <property name="jobDataAsMap"> <map> <entry key="helloWorld" value-ref="helloWorld"></entry> </map> </property> </bean> <bean id="cronEmailTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="dailyRantEmailJob" /> <property name="cronExpression" value="0-59 0-59 0-23 * * ?" /> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronEmailTrigger"/> </list> </property> </bean> </beans>

第四步:启动Test.java

package com.springinaction.quartz; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { new ClassPathXmlApplicationContext("springquartz.xml"); } }

异常的处理:

nested exception is java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.orderedSet(Ljava/util/Set;)Ljava/util/Set; 出现这个异常的原因是:commons-collections.jar版本太低,可以到http://commons.apache.org/collections/下载最commons-collections-3.2.1-bin.tar.gz ,注意在user library中需要将这个jar包移到最前面,这样就可以最先被引用。

你可能感兴趣的:(spring Quartz用法)