天天看點

Spring整合TimerTask實作定時任務排程

一. 前言

近期在公司的項目中用到了定時任務, 本篇博文将會對TimerTask定時任務進行總結, 事實上TimerTask在實際項目中用的不多, 

由于它不能在指定時間執行, 僅僅能讓程式依照某一個頻度執行.

二. TimerTask

JDK中Timer是一個定時器類, 它能夠為指定的定時任務進行配置.

JDK中TimerTask是一個定時任務類, 該類實作了Runnable接口, 是一個抽象類, 我們能夠繼承這個類, 實作定時任務.

/**
 * 繼承TimerTask實作定時任務
 */
public class MyTask extends TimerTask {

  @Override
  public void run() {
    String currentTime = new SimpleDateFormat("yyy-MM-dd hh:mm:ss").format(new Date());
    System.out.println(currentTime + " 定時任務正在運作...");
  }

  public static void main(String[] args) {
    Timer timer = new Timer();

    // 1秒鐘運作一次的任務, 參數為: task, delay, peroid
    timer.schedule(new MyTask(), 2000, 1000);
  }
}      

三. 整合Spring

兩個核心類: ScheduledTimerTask, TimerFactoryBean

ScheduledTimerTask類是對TimerTask的包裝器實作, 通過該類能夠為這個任務定義觸發器資訊.

TimerFactoryBean類能夠讓Spring使用配置建立觸發器, 并為一組指定的ScheduledTimerTask bean自己主動建立Timer執行個體.

1. 引入Jar包: spring.jar, commons-logging.jar

2. 定時排程業務類:

/**
 * 定時排程業務類
 */
public class TaskService extends TimerTask {
  private int count = 1;

  public void run() {
    System.out.println("第" + count + "次運作定時任務");
    count++;
  }
}      

3. 核心配置:

<?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.5.xsd">

  <bean id="taskService" class="com.zdp.service.TaskService"></bean>
  <bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
    <property name="timerTask" ref="taskService" />

    <!-- 每隔一天運作一次配置: 24*60*60*1000 -->
    <!-- 每1秒鐘程式運作一次  -->
    <property name="period" value="1000" />

    <!-- 程式啟動4秒鐘後開始運作  -->
    <property name="delay" value="4000" />
  </bean>

  <bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
    <property name="scheduledTimerTasks">
      <list>
        <ref bean="scheduledTimerTask" />
      </list>
    </property>
  </bean>
</beans>      

4. 測試類:

public class Main {
  public static void main(String[] args) {
    // 載入spring配置檔案
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    System.out.println("<<-------- 啟動定時任務 -------- >>");
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
      try {
        if (reader.readLine().equals("quit")) {
          System.out.println("<<-------- 退出定時任務 -------- >>");
          System.exit(0);
        }
      } catch (IOException e) {
        throw new RuntimeException("error happens...", e);
      }
    }
  }
}