---
title: "Spring中使用TimerTask定制任务"
author: "yefriendly"
date: "2009-06-08T21:08:53Z"
tags: []
slug: "spring-timertask"
draft: false
lastmod: "2009-06-08T21:10:49Z"
id: 404368
url: "https://yefriendly.iteye.com/blog/404368"
---

**任务计划**

  对于任务计划定时执行，JDK提供了java.util.Timer与java.util.TimerTask类。而Timer功能有限，只能指定任务与任务之间的周期，无法指定某个时间点定时执行任务，可以使用Quartz,它提供了更多的任务计划功能。

### 1：使用TimerTask

**A: 定义１个计划任务**

**package** onlyfun.bb.timertask;

**import** java.util.TimerTask;

/\**

 * １：首先定义１个计划任务(Task),继承TimerTask.

 * ２：使用ScheduledTimerTask定义任务的执行周期．

 * **@author** Administrator

 *

 \*/

**public** **class** DemoTask **extends** TimerTask {

@Override

    **public** **void** run() {

       // **TODO** Auto-generated method stub

       System.*out*.println("Takk is executed");

}

}

**B: 在applicationContext.xml配置如下：**

 &lt;beans&gt;

 &lt;bean id="demoTask" class="onlyfun.bb.timertask.DemoTask"&gt;&lt;/bean&gt;

 

 &lt;bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;

   &lt;property name="timerTask" ref="demoTask"&gt;&lt;/property&gt;

   &lt;property name="period" value="1000"&gt;&lt;/property&gt;

   &lt;!--period定义任务执行间隔，单位毫秒--&gt;

   &lt;property name="delay" value="1000"&gt;&lt;/property&gt;

   &lt;!--delay定义启动后，在第一次执行任务前要延迟多少毫秒--&gt;

 &lt;/bean&gt;

 

 &lt;bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean"&gt;

    &lt;property name="scheduledTimerTasks"&gt;

      &lt;list&gt;

        &lt;ref bean="scheduledTimerTask"/&gt;

      &lt;/list&gt;

    &lt;/property&gt;

 &lt;/bean&gt;

**注意：**

 

**C: 测试**

package onlyfun.bb.timertask;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.\*;

import java.util.Timer;

public class TestDemoTask {

       public static void main(String\[] args)throws IOException {

              // TODO Auto-generated method stub

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

              System.out.println("启动Task:");

              System.out.println("请输入 exit 结束Task:");

              //A处

             

              BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));

              while(true){

                     if(reader.readLine().equals("exit")) break;

                     }

              //此句可以放在A处

              Timer timer=(Timer)context.getBean("timerFactoryBean");

              timer.cancel();

}  }

 

### 2：使用MethodInvokingTimerTaskFactoryBean制订任务

使用Spring，不一定要继承TimerTask来定义１个Task.

Spring也可以使用MethodInvokingTimerTaskFactoryBean类直接指定执行某个对象的方法．

**A: 制定任务（普通类，不需要继承TimerTask）**

**package** onlyfun.bb.timertask;

**public** **class** DemoTask2 {

    **public** **void** execute(){

       System.*out*.println("Task is executed without extends TimerTask");

    }

}

**B: 配置（注意与方法1的比较：粗体部分）**

&lt;!-- task: without extends TimerTask --&gt;

 &lt;bean id="demoTask2" class="onlyfun.bb.timertask.DemoTask2"&gt;&lt;/bean&gt;

 **&lt;bean id="timerTaksBean" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"&gt;**

    **&lt;property name="targetObject" ref="demoTask2"&gt;&lt;/property&gt;**

    **&lt;property name="targetMethod" value="execute"&gt;&lt;/property&gt;**

 **&lt;/bean&gt;**

 

&lt;bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;

   **&lt;property name="timerTask" ref="timerTaksBean"&gt;&lt;/property&gt;**

   &lt;property name="period" value="1000"&gt;&lt;/property&gt;

   &lt;property name="delay" value="1000"&gt;&lt;/property&gt;

 &lt;/bean&gt;

 

 &lt;bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean"&gt;

    &lt;property name="scheduledTimerTasks"&gt;

      &lt;list&gt;

        &lt;ref bean="scheduledTimerTask"/&gt;

      &lt;/list&gt;

    &lt;/property&gt;

 &lt;/bean&gt;

**C： 测试——与方法1的测试一样。**

 

 

### 3：使用TimerTask定制任务，程序直接启动任务。

**(参考D:/workspace/SpringTimer项目)**

**3．1 定制任务类MainTask**

**package** timer;

**import** java.util.TimerTask;

**public** **class** MainTask **extends** TimerTask {

@Override

    **public** **void** run() {

       // **TODO** Auto-generated method stub

        System.*out*.println("你好 等会而见");

    }

}

**3．2 采用程序直接启动的方式启动定时任务**

**package** timer;

**import** java.util.Timer;

**public** **class** TestMainTask {

    **public** **void** run(){

       Timer timer=**new** Timer();

       timer.schedule(**new** MainTask(),2000,1000);

       //（定时任务类，任务首次启动时间，间隔时间）。其中任务首次启动时间以ms为单位，计算延期时间。

    }

   

    **public** **static** **void** main(String args\[]){

       //运行下面２句可以直接启动任务

       TestMainTask tm=**new** TestMainTask();

       tm.run();

       }

}

运行程序输出：

你好 等会而见

你好 等会而见

你好 等会而见

**3．3 采用Spring框架管理任务类，并且容器来启动启动定时任务**

**添加配置：applicationContext.xml (该文件默认在src下 )**

&lt;beans&gt;

    &lt;bean id="mainTask" class="timer.MainTask"&gt;&lt;/bean&gt;

    &lt;!-- 注册定时器信息 --&gt;

    &lt;bean id="sTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;

       &lt;property name="delay"&gt;

           &lt;value&gt;1000&lt;/value&gt;

       &lt;/property&gt;