天天看點

Quartz2.1.5學習(一)

Quartz 是一個功能強大的作業排程工具。

      日程安排好了之後,我們就要去執行,Quartz可以計劃的執行這些任務,定時、循環或在某一個時間來執行我們需要做的事,用到Quartz可以很好的解決我們平時工作中的瑣碎麻煩的事:比如,資料庫系統需要我們每天23:50的時候需要執行一次備份,每月的15号需要将公司賬目平台裡的工資表導出……有了Quartz可以很好的來解決這些問題,不需要我們手動來執行。

我下載下傳的是目前最新版本quartz-2.1.5。下載下傳後,我們的壓縮包裡有:

docs檔案夾:裡面是Quartz的API、表資料庫、圖檔檔案夾

examples:裡面是官方提供的一些DEMO

lib:第三方庫,一些特性需要它們依靠

quartz:源碼

quartz-*:支援各架構的源碼

*.jar:一些JAR包

……

下面我們可以将官網下載下傳的安裝包裡提供的例子導入到自己的IDE中,我使用的是MyEclipse8.5+Apache Tomcat6.0+JDK1.6.0。

來看官網提供的第一個例子:example1

注:将resources這個包裡的log4j.xml、quartz_priority.properties這兩個拷貝到src下,完整的如下:

HelloJob.java

package org.quartz.examples.example1; 

import java.util.Date; 

import org.slf4j.Logger; 

import org.slf4j.LoggerFactory; 

import org.quartz.Job; 

import org.quartz.JobExecutionContext; 

import org.quartz.JobExecutionException; 

/** 

 * 這僅僅是一個列印"hello world"的工作例子 

 * @author 束洋洋 

 * @createDate 2012-6-4下午10:13:34 

 */ 

public class HelloJob implements Job { 

    private static Logger _log = LoggerFactory.getLogger(HelloJob.class); 

    /** 

     * <p> 

     * Empty constructor for job initilization 

     * </p> 

     * Quartz requires a public empty constructor so that the 

     * scheduler can instantiate the class whenever it needs. 

     */ 

    public HelloJob() { 

    } 

     * Called by the <code>{@link org.quartz.Scheduler}</code> when a 

     * <code>{@link org.quartz.Trigger}</code> fires that is associated with 

     * the <code>Job</code>. 

     *  

     * @throws JobExecutionException 

     *             if there is an exception while executing the job. 

    public void execute(JobExecutionContext context) 

        throws JobExecutionException { 

        // Say Hello to the World and display the date/time 

        _log.info("Hello World! - " + new Date()); 

這是任務執行類,需要實作job接口,在execute方法裡寫具體的任務實作。org.quartz.JobExecutionContext這個對象可以擷取到任務排程程式裡傳遞過來的參數,後面講到。

SimpleExample.java(任務排程程式類)

Quartz架構執行任務排程步驟:

建立Scheduler對象,可以從SchedulerFactory類裡取得。

      SchedulerFactory sf = new StdSchedulerFactory();

      Scheduler sched = sf.getScheduler();

建立JobDetail對象,執行任務排程的方法,這個方法實作了job接口

      JobDetail job = newJob(HelloJob.class)

            .withIdentity("job1", "group1")

            .build();

構造job的觸發器對象,可以指定任務時間或周期。

      Trigger trigger = newTrigger()

            .withIdentity("trigger1", "group1")

            .startAt(runTime)

告訴Quartz安排工作使用的觸發器(安排任務)

      sched.scheduleJob(job, trigger);

開始排程任務程式

      sched.start();

暫停排程任務,調用standby()使Scheduler回到"stand-by"模式。再次調用start()方法,使Scheduler回到運作狀态。 

      sched.standby();

停止排程任務,停止後不能重新開始。 

      sched.shutdown(true);

/*  

 * Copyright 2005 - 2009 Terracotta, Inc.  

 *  

 * Licensed under the Apache License, Version 2.0 (the "License"); you may not  

 * use this file except in compliance with the License. You may obtain a copy  

 * of the License at  

 *   http://www.apache.org/licenses/LICENSE-2.0  

 *    

 * Unless required by applicable law or agreed to in writing, software  

 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT  

 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the  

 * License for the specific language governing permissions and limitations  

 * under the License. 

import static org.quartz.JobBuilder.newJob; 

import static org.quartz.TriggerBuilder.newTrigger; 

import static org.quartz.DateBuilder.*; 

import org.quartz.JobDetail; 

import org.quartz.Scheduler; 

import org.quartz.SchedulerFactory; 

import org.quartz.Trigger; 

import org.quartz.impl.StdSchedulerFactory; 

 * This Example will demonstrate how to start and shutdown the Quartz  

 * scheduler and how to schedule a job to run in Quartz. 

 * @author Bill Kratzer 

public class SimpleExample { 

    public void run() throws Exception { 

        Logger log = LoggerFactory.getLogger(SimpleExample.class); 

        log.info("------- Initializing ----------------------"); 

        // First we must get a reference to a scheduler 

        SchedulerFactory sf = new StdSchedulerFactory(); 

        Scheduler sched = sf.getScheduler(); 

        log.info("------- Initialization Complete -----------"); 

        // computer a time that is on the next round minute 

        Date runTime = evenMinuteDate(new Date()); 

        log.info("------- Scheduling Job  -------------------"); 

        // define the job and tie it to our HelloJob class 

        JobDetail job = newJob(HelloJob.class) 

            .withIdentity("job1", "group1") 

            .build(); 

        // Trigger the job to run on the next round minute 

        Trigger trigger = newTrigger() 

            .withIdentity("trigger1", "group1") 

            .startAt(runTime) 

        // Tell quartz to schedule the job using our trigger 

        sched.scheduleJob(job, trigger); 

        log.info(job.getKey() + " will run at: " + runTime);   

        // Start up the scheduler (nothing can actually run until the  

        // scheduler has been started) 

        sched.start(); 

        log.info("------- Started Scheduler -----------------"); 

        // wait long enough so that the scheduler as an opportunity to  

        // run the job! 

        log.info("------- Waiting 10 seconds... -------------"); 

        try { 

            // wait 65 seconds to show job 

            Thread.sleep(10000);  

            // executing... 

        } catch (Exception e) { 

        } 

        log.info("------- 暫停下程式... -------------"); 

        sched.standby(); 

        Thread.sleep(10000);  

        log.info("------- 重新開始程式... -------------"); 

        // shut down the scheduler 

        log.info("------- Shutting Down ---------------------"); 

        sched.shutdown(true); 

        log.info("------- Shutdown Complete -----------------"); 

    public static void main(String[] args) throws Exception { 

        SimpleExample example = new SimpleExample(); 

        example.run(); 

控制台列印資訊:

[INFO] 06 六月 09:29:06.906 下午 main [org.quartz.examples.example1.SimpleExample] 

------- Initializing ---------------------- 

[INFO] 06 六月 09:29:07.062 下午 main [org.quartz.impl.StdSchedulerFactory] 

Using default implementation for ThreadExecutor 

[INFO] 06 六月 09:29:07.078 下午 main [org.quartz.simpl.SimpleThreadPool] 

Job execution threads will use class loader of thread: main 

[INFO] 06 六月 09:29:07.125 下午 main [org.quartz.core.SchedulerSignalerImpl] 

Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl 

[INFO] 06 六月 09:29:07.125 下午 main [org.quartz.core.QuartzScheduler] 

Quartz Scheduler v.2.1.5 created. 

[INFO] 06 六月 09:29:07.125 下午 main [org.quartz.simpl.RAMJobStore] 

RAMJobStore initialized. 

Scheduler meta-data: Quartz Scheduler (v2.1.5) 'DefaultQuartzScheduler' with instanceId 'NON_CLUSTERED' 

  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally. 

  NOT STARTED. 

  Currently in standby mode. 

  Number of jobs executed: 0 

  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads. 

  Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered. 

[INFO] 06 六月 09:29:07.125 下午 main [org.quartz.impl.StdSchedulerFactory] 

Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties' 

Quartz scheduler version: 2.1.5 

[INFO] 06 六月 09:29:07.125 下午 main [org.quartz.examples.example1.SimpleExample] 

------- Initialization Complete ----------- 

[INFO] 06 六月 09:29:07.140 下午 main [org.quartz.examples.example1.SimpleExample] 

------- Scheduling Job  ------------------- 

[INFO] 06 六月 09:29:07.171 下午 main [org.quartz.examples.example1.SimpleExample] 

group1.job1 will run at: Wed Jun 06 21:30:00 CST 2012 

[INFO] 06 六月 09:29:07.171 下午 main [org.quartz.core.QuartzScheduler] 

Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started. 

------- Started Scheduler ----------------- 

------- Waiting 10 seconds... ------------- 

[INFO] 06 六月 09:29:17.171 下午 main [org.quartz.examples.example1.SimpleExample] 

------- 暫停下程式... ------------- 

[INFO] 06 六月 09:29:17.171 下午 main [org.quartz.core.QuartzScheduler] 

Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused. 

[INFO] 06 六月 09:29:27.171 下午 main [org.quartz.examples.example1.SimpleExample] 

------- 重新開始程式... ------------- 

[INFO] 06 六月 09:29:27.171 下午 main [org.quartz.core.QuartzScheduler] 

------- Shutting Down --------------------- 

Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down. 

[INFO] 06 六月 09:29:27.578 下午 main [org.quartz.core.QuartzScheduler] 

Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete. 

[INFO] 06 六月 09:29:27.578 下午 main [org.quartz.examples.example1.SimpleExample] 

------- Shutdown Complete ----------------- 

這裡使用了Thread.sleep(10000); 是為了給排程的程式有時間執行。

=======================================================================

以上屬于個人觀點,難免有錯誤,如發現錯誤請留言告之,我會訂正的。

本文轉自shyy8712872 51CTO部落格,原文連結:http://blog.51cto.com/shuyangyang/890639,如需轉載請自行聯系原作者