Java+Tomcatでタスクを定期的に実行する方法 実装一例

2011/11/10 19:21Update
TAGS: ServletContextListener | Java | Tomcat | Servlet | リスナー | ジョブ | タスク | Timer | タイマー

Java+Tomcatでタスクを定期的に実行する方法 の一例。

コード例:

package com.syboos.timer;

//import package HERE TODO
...


public class TimerListener implements ServletContextListener {
    //タイマーの起動時間:24:00
    private static final int HOUR = 24;
    private static final int MINUTE = 0;
    private static final int SECOND = 0;
    private Timer timer = null;

    public void contextDestroyed(ServletContextEvent event) {//コンテキストの
        timer.cancel();
            event.getServletContext().log("Timer is canceled.");
    }

    public void contextInitialized(ServletContextEvent event) {//コンテキストを初期化時
            timer=new Timer(true);
            event.getServletContext().log("Timer is started.");
            Calendar calendar = Calendar.getInstance(); 
            calendar.set(Calendar.HOUR_OF_DAY, HOUR);
            calendar.set(Calendar.MINUTE, MINUTE); 
            calendar.set(Calendar.SECOND, SECOND);
        
        //タイマーに実行したいジョブを設定
            timer.schedule(new MyJob(event.getServletContext()), calendar.getTime(), 
                1*24*60*60*1000);
    }
}



web.xml
<!-- タイマー設定 -->
<listener>
    <listener-class>com.syboos.timer.TimerListener</listener-class>
</listener>


参考資料


Quartz Enterprise Job Scheduler - J2SE、J2EEアプリケーション用のオープンソースジョブスケジューラ

有关作者
Syboos.jp編集長AJavaやオープンソース情報の執筆、Webサイトの開発や運営全般の業務に携わる。

Sponsored Link


Comments

用户名 (required)

Email (will not be published) (required)

URL

Evaluation