Springの2つのタイミングタスクを実現しました。


方法一Timerを利用したタイミングタスクの開発
2ステップ分:
第1ステップは、タイミングタスククラスを作成します。
第2ステップは、タイミングタスクを実行します。
          2種類の運転方式に分かれています。1)プログラムが直接起動します。
                                  2)web傍受方式。
 
1)タイミングタスククラスを作成するコード例は以下の通りです。
package com.gc.action;
import java.util.TimerTask;
class MainTask extends TimerTask{
	public  void run() 
	{
		System.out.println("Hello World!");
	}
}
 2)タイミングタスクを実行します。
       (1)プログラム直接起動方式。
package com.gc.action;
import java.util.Timer;
class Main 
{
	public static void main(String[] args) 
	{
		System.out.println("1Hello World!");
		Timer timer = new Timer();
		timer.schedule(new MainTask(),0,1*1000);
		System.out.println("2Hello World!");
	}
}
 コードの説明:timer.schedule()メソッドパラメータの説明――timer.schedule(タイムタスククラス、最初の起動時間、間隔時間)は、このように1つの間隔を過ぎるごとに1回のタイミングタスククラスコードを実行します。
 
実行結果:
D:\java\editplus>java com.gc.action.Main
1Hello World!
2Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
……
 
  (2)web傍受方式の起動。
 
package com.gc.action;
import java.util.Timer;
class  BindLoader implements ServletContextListener{
	private Timer timer = null;

	//           
	public  void contextInitialized(ServletContextEvent sce){
		timer = new Timer();
		timer.schedule(new MainTask(),0, 1*1000);
		System.out.println("Hello World!");
	}

	//          
	public void contextDestroyed(ServletContextEvent sce){
		timer.cancel();
	}
}
コードの説明:モニターはjavax.servlet.Servlet Contect Listenerインターフェースを実現しなければなりません。
また、web.xmlに傍受クラスを配置する必要があります。
<listener>
    <listener-class>com.gc.action.BindLoader</listener-class>
</listener>
 
方法二、Quartz方法でタイミングタスクを実現します。