quartz任务时间调度入门使用(一)
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 -----------------