Quartz 是 OpenSymphony 開源組織在任務調度領域的一個開源項目,完全基於 Java 實現。
作為一個優秀的開源調度框架,Quartz 具有以下特點:
- 強大的調度功能,例如支持豐富多樣的調度方法,可以滿足各種常規及特殊需求;
- 靈活的應用方式,例如支持任務和調度的多種組合方式,支持調度數據的多種存儲方式;
- 分布式和集群能力,Terracotta 收購后在原來功能基礎上作了進一步提升。本文暫不討論該部分內容
另外,作為 Spring 默認的調度框架,Quartz 很容易與 Spring 集成實現靈活可配置的調度功能。
下面是本文中用到的一些專用詞匯,在此聲明:
- scheduler:
- 任務調度器
- trigger:
- 觸發器,用於定義任務調度時間規則
- job:
- 任務,即被調度的任務
- misfire:
- 錯過的,指本來應該被執行但實際沒有被執行的任務調度
1、首先下載一份quartz源文件,下載地址:http://www.quartz-scheduler.org/,解壓出來,我的是quartz-2.2.3版本,也可以直接發郵件給我912547587@qq.com索要,我解壓出來,如圖所示:
2、打開文件夾quartz-2.2.3,里面內容如圖所示:
docs:一些文件信息;
examples:官方的案例;
javadoc:官方API;
lib:開發過程中所使用的jar包;
licenses:版本的序列號
src:quartz源碼信息;
3、根據官方案例庫,我們來學習一下他們調用過程,首先創建一個eclipse的Java工程,將項目導進去,創建兩個Java文件和一個log4j.xml文件,eclipse結構如圖:
SimpleExample.jav 1
2 package org.quartz.examples.example1; 3 4 import static org.quartz.DateBuilder.evenMinuteDate; 5 import static org.quartz.JobBuilder.newJob; 6 import static org.quartz.TriggerBuilder.newTrigger; 7 8 import org.quartz.JobDetail; 9 import org.quartz.Scheduler; 10 import org.quartz.SchedulerFactory; 11 import org.quartz.Trigger; 12 import org.quartz.impl.StdSchedulerFactory; 13 import org.slf4j.Logger; 14 import org.slf4j.LoggerFactory; 15 16 import java.util.Date; 17 18 /** 19 * This Example will demonstrate how to start and shutdown the Quartz scheduler and how to schedule a job to run in 20 * Quartz. 21 * 22 * @author Bill Kratzer 23 */ 24 public class SimpleExample { 25 26 public void run() throws Exception { 27 Logger log = LoggerFactory.getLogger(SimpleExample.class); 28 29 log.info("------- Initializing ----------------------"); 30 31 // First we must get a reference to a scheduler,首先我們獲取一個任務調度器 32 SchedulerFactory sf = new StdSchedulerFactory(); 33 Scheduler sched = sf.getScheduler(); 34 35 log.info("------- Initialization Complete -----------"); 36 37 // computer a time that is on the next round minute獲取下一個整點分鍾,比如現在是11:20:23,獲取的時間就是11:21:00 38 Date runTime = evenMinuteDate(new Date()); 39 40 log.info("------- Scheduling Job -------------------"); 41 42 // define the job and tie it to our HelloJob class定義一個任務,並把要執行的邏輯告訴Job任務 43 JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build(); 44 45 // Trigger the job to run on the next round minute,觸發器,當下一個整點分鍾執行HelloJOb中的邏輯
46 Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build(); 47 48 // Tell quartz to schedule the job using our trigger將任務和觸發器加入到任務調度器中 49 sched.scheduleJob(job, trigger); 50 log.info(job.getKey() + " will run at: " + runTime); 51 52 // Start up the scheduler (nothing can actually run until the 53 // scheduler has been started)任務啟動 54 sched.start(); 55 56 log.info("------- Started Scheduler -----------------"); 57 58 // wait long enough so that the scheduler as an opportunity to 59 // run the job!等待10s中 60 log.info("------- Waiting 10 seconds... -------------"); 61 try { 62 // wait 65 seconds to show job 63 Thread.sleep(10L * 1000L); 64 // executing... 65 } catch (Exception e) { 66 // 67 } 68 69 // shut down the scheduler任務自動關閉 70 log.info("------- Shutting Down ---------------------"); 71 sched.shutdown(true); 72 log.info("------- Shutdown Complete -----------------"); 73 } 74 75 public static void main(String[] args) throws Exception { 76 77 SimpleExample example = new SimpleExample(); 78 example.run(); 79 80 } 81 82 }
HelloJob.java
1 /* 2 * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy 6 * of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations 14 * under the License. 15 * 16 */ 17 18 package org.quartz.examples.example1; 19 20 import java.util.Date; 21 22 import org.slf4j.Logger; 23 import org.slf4j.LoggerFactory; 24 import org.quartz.Job; 25 import org.quartz.JobExecutionContext; 26 import org.quartz.JobExecutionException; 27 28 /** 29 * <p> 30 * This is just a simple job that says "Hello" to the world. 31 * </p> 32 * 33 * @author Bill Kratzer 34 */ 35 public class HelloJob implements Job { 36 37 private static Logger _log = LoggerFactory.getLogger(HelloJob.class); 38 39 /** 40 * <p> 41 * Empty constructor for job initilization 42 * </p> 43 * <p> 44 * Quartz requires a public empty constructor so that the 45 * scheduler can instantiate the class whenever it needs. 46 * </p> 47 */ 48 public HelloJob() { 49 } 50 51 /** 52 * <p> 53 * Called by the <code>{@link org.quartz.Scheduler}</code> when a 54 * <code>{@link org.quartz.Trigger}</code> fires that is associated with 55 * the <code>Job</code>. 56 * </p> 57 * 58 * @throws JobExecutionException 59 * if there is an exception while executing the job. 60 */ 61 public void execute(JobExecutionContext context) 62 throws JobExecutionException { 63 64 // Say Hello to the World and display the date/time要執行的業務邏輯 65 _log.info("Hello World! - " + new Date()); 66 } 67 68 }
log4j.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="default" class="org.apache.log4j.ConsoleAppender"> <param name="target" value="System.out"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%p] %d{dd MMM hh:mm:ss.SSS aa} %t [%c]%n%m%n%n"/> </layout> </appender> <logger name="org.quartz"> <level value="info" /> </logger> <root> <level value="info" /> <appender-ref ref="default" /> </root> </log4j:configuration>
執行結果日志:
[INFO] 2017-03-20 18:31:36 992 main [org.quartz.examples.example1.SimpleExample]
------- Initializing ----------------------
[INFO] 2017-03-20 18:31:37 028 main [org.quartz.impl.StdSchedulerFactory]
Using default implementation for ThreadExecutor
[INFO] 2017-03-20 18:31:37 032 main [org.quartz.simpl.SimpleThreadPool]
Job execution threads will use class loader of thread: main
[INFO] 2017-03-20 18:31:37 044 main [org.quartz.core.SchedulerSignalerImpl]
Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
[INFO] 2017-03-20 18:31:37 045 main [org.quartz.core.QuartzScheduler]
Quartz Scheduler v.2.2.3 created.
[INFO] 2017-03-20 18:31:37 045 main [org.quartz.simpl.RAMJobStore]
RAMJobStore initialized.
[INFO] 2017-03-20 18:31:37 047 main [org.quartz.core.QuartzScheduler]
Scheduler meta-data: Quartz Scheduler (v2.2.3) '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] 2017-03-20 18:31:37 047 main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
[INFO] 2017-03-20 18:31:37 047 main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler version: 2.2.3
[INFO] 2017-03-20 18:31:37 047 main [org.quartz.examples.example1.SimpleExample]
------- Initialization Complete -----------
[INFO] 2017-03-20 18:31:37 048 main [org.quartz.examples.example1.SimpleExample]
------- Scheduling Job -------------------
[INFO] 2017-03-20 18:31:37 058 main [org.quartz.examples.example1.SimpleExample]
group1.job1 will run at: Mon Mar 20 18:32:00 CST 2017
[INFO] 2017-03-20 18:31:37 058 main [org.quartz.core.QuartzScheduler]
Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
[INFO] 2017-03-20 18:31:37 059 main [org.quartz.examples.example1.SimpleExample]
------- Started Scheduler -----------------
[INFO] 2017-03-20 18:31:37 059 main [org.quartz.examples.example1.SimpleExample]
------- Waiting 65 seconds... -------------
[INFO] 2017-03-20 18:31:47 060 main [org.quartz.examples.example1.SimpleExample]
------- Shutting Down ---------------------
[INFO] 2017-03-20 18:31:47 060 main [org.quartz.core.QuartzScheduler]
Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.
[INFO] 2017-03-20 18:31:47 060 main [org.quartz.core.QuartzScheduler]
Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.
[INFO] 2017-03-20 18:31:47 535 main [org.quartz.core.QuartzScheduler]
Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.
[INFO] 2017-03-20 18:31:47 535 main [org.quartz.examples.example1.SimpleExample]
------- Shutdown Complete -----------------