ホームページ  >  記事  >  Java  >  Spring は TimerTask を統合してスケジュールされたタスクのスケジューリングを実装します

Spring は TimerTask を統合してスケジュールされたタスクのスケジューリングを実装します

高洛峰
高洛峰オリジナル
2017-02-07 15:27:351586ブラウズ

1. はじめに

最近、会社のプロジェクトで時間指定タスクが使用されていますが、このブログ記事では TimerTask の時間指定タスクについてまとめます。 . プログラムは特定の頻度でのみ実行できます。

2. 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); 
  } 
}

3. Spring の 2 つのコア クラスを統合します: ScheduledTimerTask、TimerFactoryBean

ScheduledTimerTask クラスは、This クラスを介して TimerTask のラッパー実装です。

TimerFactoryBean クラスを使用すると、Spring は設定を使用してトリガーを作成し、指定された一連の ScheduledTimerTask Bean の Timer インスタンスを自動的に作成できます: 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>

以上がこの記事の全内容であり、皆様の学習に役立つことを願っています。詳細については、PHP 中国語 Web サイトをご覧ください。


TimerTask を統合してスケジュールされたタスクのスケジューリングを実装する Spring に関連するその他の記事については、PHP 中国語 Web サイトに注目してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。