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" /><bean id="pageReportTask" /><!-- ScheduledTimerTask设置定时器属性 : period=定时器周期;delay=延迟多久启动 86400000代表24个小时;timerTask=执行定时任务的类对象 --> <bean id="emailReportScheduleReportTask" ref="emailReportTask" /> <property name="period" value="2000" /> <property name="delay" value="1000" /> </bean> <bean id="pageReportScheduleReportTask" ref="pageReportTask" /> <property name="period" value="2000" /> </bean> <!-- Spring的TimerFactoryBean负责启动定时任务; scheduledTimerTasks = 需要启动的定时器任务的列表--> <bean name="code">public class TestBaseService {protected ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:resource/spring.xml"});@Testpublic void timer(){try{// 这个是主线程,如果结束了,则定时器也会结束,所有设置时间要长Thread.sleep(36 * 1000);}catch(Exception e){e.printStackTrace();} }}??
参考文献:
spring 定时器如何配置??Spring中Quartz的配置??spring定时任务之quartz??Spring定时器的两种实现方式??