`

spring学习系列 -- 定时器一TimerTask

阅读更多

 

spring定时器一般有两种

TimerTask、Quartz。本节只讲TimerTask

需要的包

aopalliance-1.0.jar

commons-logging-1.1.1.jar

spring-aop-3.0.6.RELEASE.jar

spring-asm-3.0.6.RELEASE.jar

spring-beans-3.0.6.RELEASE.jar

spring-context-3.0.6.RELEASE.jar

spring-core-3.0.6.RELEASE.jar

spring-expression-3.0.6.RELEASE.jar

 

TimerTask实例:同时启动2个定时器,执行任务

定时执行任务的类继承TimerTask:

public class EmailReportTask extends TimerTask{   
    @Override   
    public void run() {   
        System.out.println(" EmailReportTask Run... ");
    }     
} 

public class PageReportTask extends TimerTask{   
    @Override   
    public void run() {   
        System.out.println("PageReportTask Run...");
    }     
}   

 

spring的配置文件:

  	<!--  Bean  --> 
	<bean id="emailReportTask" class="com.hry.spring.timertask.EmailReportTask" />
	<bean id="pageReportTask" class="com.hry.spring.timertask.PageReportTask" />

	<!-- ScheduledTimerTask设置定时器属性 : period=定时器周期;delay=延迟多久启动 
		 86400000代表24个小时;timerTask=执行定时任务的类对象  --> 
	<bean id="emailReportScheduleReportTask" 
		class="org.springframework.scheduling.timer.ScheduledTimerTask">   
		<property name="timerTask" ref="emailReportTask" />   
		<property name="period" value="2000" />   
		<property name="delay" value="1000" />   
	</bean> 
	<bean id="pageReportScheduleReportTask" 
		class="org.springframework.scheduling.timer.ScheduledTimerTask">   
		<property name="timerTask" ref="pageReportTask" />   
		<property name="period" value="2000" />    
	</bean> 

 	<!-- Spring的TimerFactoryBean负责启动定时任务; 
 		scheduledTimerTasks = 需要启动的定时器任务的列表-->
 	<bean class="org.springframework.scheduling.timer.TimerFactoryBean">   
		<property name="scheduledTimerTasks">   
	   		<list>
	   			<ref bean="emailReportScheduleReportTask"/>
	   			<ref bean="pageReportScheduleReportTask"/>
	   		</list>  
		</property>   
	</bean> 
 

测试代码:

public class TestBaseService {
	protected ApplicationContext ctx = new ClassPathXmlApplicationContext(
			new String[]{
					"classpath:resource/spring.xml"
			}
	);

	@Test
	public void timer(){
		try{
			// 这个是主线程,如果结束了,则定时器也会结束,所有设置时间要长
			Thread.sleep(36 * 1000);
		}catch(Exception e){
			e.printStackTrace();
		}
 
	}
}
 

 

参考文献:

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics