Spring使用TimerTask配置调度事务

来源:互联网 发布:知乎日报文章搜索不到 编辑:程序博客网 时间:2024/06/04 19:54

首先我们编写调度服务,继承java.util.TimerTask

 

package TimerTest;

import java.util.Date;
import java.util.TimerTask;

public class TimerService extends TimerTask {    
    
public void run() {
        System.out.println(
new Date().getSeconds());        
    }

}

配置文件:

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
  
<!-- 配置调度方法 -->
  
<bean id="reportTask" class="TimerTest.TimerService"/>
  
<!-- 配置定时器任务 -->
  
<bean id="scheduledReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
    
<property name="timerTask">
      
<ref bean="reportTask"/>
    
</property>
     
<property name="period">
      
<value>1000</value>
    
</property>

  
</bean>
  
<!-- 启动定时器 -->
  
<bean id="start" class="org.springframework.scheduling.timer.TimerFactoryBean">
    
<property name="scheduledTimerTasks">
      
<list>
      
<ref bean="scheduledReportTask"/>
    
</list>
    
</property>
  
</bean>
</beans>

 

测试代码:

 

package TimerTest;

import java.io.File;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;




public class TestTimer {

    
public static void main(String[] args) {

        String filePath
=System.getProperty("user.dir")+File.separator+"TimerTest"+File.separator+"hello.xml";
        
        ApplicationContext  context
=new FileSystemXmlApplicationContext(filePath);
        
        
//如果使用BeanFactory,则必须调用factory.getBean("start"),才能启动调度任务
        
        


    }

}

 

运行结果:

2007-6-5 23:16:24 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@109a4c: display name [org.springframework.context.support.FileSystemXmlApplicationContext@109a4c]; startup date [Tue Jun 05 23:16:24 CST 2007]; root of context hierarchy
2007-6-5 23:16:24 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [E:/项目/SpringInActionStudy/TimerTest/hello.xml]
2007-6-5 23:16:24 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.FileSystemXmlApplicationContext@109a4c]: org.springframework.beans.factory.support.DefaultListableBeanFactory@cd2c3c
2007-6-5 23:16:24 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@cd2c3c: defining beans [reportTask,scheduledReportTask,start]; root of factory hierarchy
2007-6-5 23:16:24 org.springframework.scheduling.timer.TimerFactoryBean afterPropertiesSet
信息: Initializing Timer
25
26
27

可以看到,每隔一秒就打印当前时间的秒数

原创粉丝点击