目的:
写两个任务,分别是TestJob和TestJob2。TestJob每个10秒钟打印一行文字到控制台,TestJob2每个一分钟打印一行文字到控制台。
搭建环境:
用MyEclipase或Eclipase创建一个Java Project。在项目下创建lib目录,放入必要的Spring的jar文件。结构如下图:
任务Java代码:
package com.test; /** * 任务一 * * @author 530 * */ public class TestJob { private static int count = 1; /** * 任务方法 */ public void work() { System.out.println("TestJob " + count++); } }
package com.test; /** * 任务二 * * @author 530 * */ public class TestJob2 { private static int count = 1; /** * 任务方法 */ public void runJob() { System.out.println("TestJob2 " + count++); } }
配置文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 将要调用的工作类的Bean --> <bean id="test" class="com.test.TestJob"/> <bean id="test2" class="com.test.TestJob2"/> <!-- 将调用对象和调用对象的方法定义成一个任务 --> <bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 调用的类 --> <property name="targetObject" ref="test"/> <!-- 调用类中的方法 --> <property name="targetMethod" value="work"/> </bean> <bean id="jobtask2" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="test2"/> <property name="targetMethod" value="runJob"/> </bean> <!-- 定义每个任务的触发时间 --> <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="jobtask"/> <!-- cron表达式 --> <property name="cronExpression"> <!-- 每隔10秒钟调用一次 --> <value>0/10 * * * * ?</value> </property> </bean> <bean id="doTime2" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="jobtask2"/> <property name="cronExpression"> <!-- 每隔1分钟调用一次 --> <value>0 0/1 * * * ?</value> </property> </bean> <!-- 总管理类,管理所有的定时任务,如果将lazy-init='false'那么容器启动就会执行调度程序 --> <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="doTime"/> <ref bean="doTime2"/> </list> </property> </bean> </beans>
测试:
package com.test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TMain { public static void main(String[] args) { System.out.println("Test start."); new ClassPathXmlApplicationContext("applicationContext.xml"); // 如果配置文件中将startQuertz bean的lazy-init设置为false 则不用实例化 // context.getBean("startQuertz"); System.out.print("Test end..\n"); } }
更多相关知识:www.bug315.com