`
2010_315
  • 浏览: 10887 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring 定时DEMO

阅读更多
定时任务如果不需要指定固定的时间点(比如晚上22:00),而只需要每隔一段时间执行任务,可以用jdk中自带的定时器来实现。Spring提供了很好的支持。

比如需要每隔一小时,就要向控制台中输出一行字符串“hello,world!”,只需要定义一个类,写一个Spring配置文件就可以了。

类用来实现具体的输出,需要继承自java.util.TimerTask。

Java代码
Package test.pupi;  
 
import java.util.List;  
import java.util.TimerTask;  
 
public class PrintHelloworld extends TimerTask {  
 
 
    @Override 
    public void run() {  
        // TODO Auto-generated method stub  
        System.out.print("hello,world!");  
    }  


Package test.pupi;

import java.util.List;
import java.util.TimerTask;

public class PrintHelloworld extends TimerTask {


@Override
public void run() {
// TODO Auto-generated method stub
System.out.print("hello,world!");
}
}

spring配置文件则也很简单,


Java代码
<?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.0.xsd">  
      
         <!-- 这个bean定义上面的那个实现定时操作的类 -->  
         <bean id="printHelloworld" 
        class="test.pupi.PrintHelloworld ">  
    </bean>  
 
      
         <!-- 这个bean定义循环定时任务,注意,period属性的单位是毫秒。3600000毫秒就是1小时 -->  
         <bean id="scheduledEmailTask" 
        class="org.springframework.scheduling.timer.ScheduledTimerTask">  
        <property name="timerTask" ref="printHelloworld" />  
        <property name="period" value="3600000" />  
    </bean>  
 
         <!-- 这个bean定义当前应用对应的所有的定时任务 -->  
    <bean  
        class="org.springframework.scheduling.timer.TimerFactoryBean">  
        <property name="scheduledTimerTasks">  
            <list>  
                <ref bean="scheduledEmailTask" />  
            </list>  
        </property>  
    </bean>  
 
 
</beans>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics