2010-11-03 quartz学习笔记一


Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that are programmed to fulfill the requirements of your application. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering. You can download the most recent stable version at  http://quartz-scheduler.org/overview/index.html .      Quartzはオープンソースのタスクスケジューリングサービスであり、数百以上の単純または複雑なタスクを同時に実行することができます.一.Quart運行環境の構築    最新バージョンをダウンロードして、解凍した後にlibディレクトリの下のすべてのjarパッケージをあなたの工事classpathの下に入れて、jarパッケージの衝突の問題に注意します.ディレクトリの下にあるquartz-all-****.jarをclasspathに追加します.xxxはバージョン番号です.二.最も簡単なhelloWorld   (1)必要なクラスの導入
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;

   (2)Schedulerを取得する
 //       
SchedulerFactory sf = new StdSchedulerFactory(); 
Scheduler sched = sf.getScheduler();

  (3)1つのタスクと1つのトリガを宣言する
 
        // computer a time that is on the next round minute
        Date runTime = TriggerUtils.getEvenMinuteDate(new Date());
        // define the job and tie it to our HelloJob class
        JobDetail job = new JobDetail("job1", "group1", HelloJob.class);
        // Trigger the job to run on the next round minute
        SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1", runTime);

 (4)タスクとトリガを関連付ける
 
   // Tell quartz to schedule the job using our trigger 
 sched.scheduleJob(job, trigger);

 (5)スケジューラの起動
 
       // Start up the scheduler (nothing can actually run until the 
        // scheduler has been started)
        sched.start();

 (6)タスクの実行後にスケジューラを閉じる
 
     // shut down the scheduler
    ///         ,          ,               
        log.info("------- Shutting Down ---------------------");
        sched.shutdown(true);
        log.info("------- Shutdown Complete -----------------");

 (7)カスタムタスククラスHelloJob
 
public class HelloJob implements Job 

 (8)Excuteメソッドの実装
 
   public void execute(JobExecutionContext context)
        throws JobExecutionException {

        // Say Hello to the World and display the date/time
        System.out.println("Hello World! - " + new Date());
    }

 (9)実行結果
 
Hello World! - Wed Nov 03 11:40:00 CST 2010