在Spring中使用任务调度功能,有二种方式。一种是使用java Timer ,Spring 对该调度API进行了抽象和封装,第二种是使用Quartz框架,Spring也对该框架进了抽象封装。
下面为第一种任务调度方式。
只需自己建二个类即可。
任务类(AddTimerTask.java)
- import java.util.TimerTask;
- public class AddTimerTask extends TimerTask {//一定行继承TimerTask或其子类
- private static int result=0;
- @Override
- public void run() {
- System.out.println(result++);
- }
- }
主类(SpringTimer.java)
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class SpringTimer {
- /**
- * @param args
- */
- public static void main(String[] args) {
- ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
- }
- }
配置文件(applicationContext.xml)
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
- <beans>
- <bean id="addTimerTask" class="AddTimerTask">
- </bean>
- <bean id="scheduledAddTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
- <property name="timerTask">
- <ref bean="addTimerTask"/>
- </property>
- <property name="delay">
- <value>2000</value>
- </property>
- <property name="period">
- <value>1000</value>
- </property>
- </bean>
- <bean class="org.springframework.scheduling.timer.TimerFactoryBean">
- <property name="scheduledTimerTasks">
- <list>
- <ref bean="scheduledAddTimerTask"/>
- </list>
- </property>
- </bean>
- </beans>
运行结果为:从程序运行后二秒钟开始,每秒钟在控制台打印一个数字,从0开始,不断的加1。