Spring任务计划(一)

 原文地址:http://blog.sina.com.cn/s/blog_4cd3174a01000av6.html

 使用TimerTask  

     package onlyfun.caterpillar;

     import java.util.TimerTask;

  public class DemoTask extends TimerTask {

       public void run(){
        System.out.println("执行任务…………");
     }

}

applicationContext.xml

<?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 id="demoTask" class="onlyfun.caterpillar.DemoTask"></bean>   
   <bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
     <property name="timerTask">
        <ref bean="demoTask"/>
     </property>
     <!--这里定义每1秒钟程序执行一次-->
     <property name="period">
       <value>1000</value>
     </property>
    <!--这里定义程序启动5秒钟后开始执行-->
     <property name="delay">
       <value>5000</value>
     </property>
   </bean>   
   <bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
     <property name="scheduledTimerTasks">
       <list>
         <ref bean="scheduledTimerTask"/>
       </list>
     </property>
   </bean>
</beans>

TimerTaskDemo.java
public static void main(String[] args) {
  new ClassPathXmlApplicationContext("applicationContext.xml");
  System.out.println("启动Task…………");  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));        
  while(true){
   try {
    if(reader.readLine().equals("exit")){
     System.exit(0);
    }
   } catch (IOException e) {
     e.printStackTrace();
   }
  }
 }

你可能感兴趣的:(Spring任务计划)