Spring中任务调度(TimerTask篇)

在Spring中实现按时任务调度除了用Quartz之外,还可以使用TimerTask。但是TimerTask适用于时间间隔相对较短的任务,如果任务时间间隔很长,比如一天执行一次,还是用Quartz要好。

1.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    
<!-- 定时执行任务的类,要继承TimerTask -->
    
<bean id="UserTimerTask" class="task.UserTimerTask"/>
    
    
<!-- 用Spring管理这个TimerTask,设定触发间隔 -->
    
<bean id="ScheduledUserTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
      
<property name="delay">
        
<value>3000</value>
      
</property>
      
<property name="period">
        
<value>3000</value>
      
</property>
      
<property name="timerTask">
        
<ref local="UserTimerTask"/>
      
</property>
    
</bean>
    
    
<!-- 启动TimerTask,TimerFactoryBean会在上下文初始化的时候自动启动task,在销毁时,自动结束task -->
    
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
     
<property name="scheduledTimerTasks">
      
<list>
        
<ref local="ScheduledUserTimerTask"/>
      
</list>
     
</property>
   
</bean>
</beans>

2.Task类
package task;

import java.util.TimerTask;

public class UserTimerTask extends TimerTask {(文章来源 www.iocblog.net)

    @Override
    
public void run() {
        
// TODO Auto-generated method stub
        System.out.println("Task started!");
    }


}


3.测试类
package test;

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

public class TimerTaskTest {

    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
         System.out.println("Test start!");
         ApplicationContext ctx 
= new ClassPathXmlApplicationContext("xml/TimerTask.xml");
         
         
//保持运行,才能看到效果
         while (true);
    
    }


}




文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。