Quartz Sheduler 入门
原文地址:http://www.quartz-scheduler.org/generated/2.2.2/html/qtz-all/
下载地址:http://quartz-scheduler.org/downloads
什么是 Quartz Scheduler?
Quartz Scheduler 是一个功能丰富,开源了的任务调度库,可以集成在几乎任何java应用程序(从最小的独立的应用程序到最大的电子商务系统)
Quartz以用来创建简单或复杂的计划表来执行数十,数百,或者成千上万个任务,这些任务被定义为标准的java组件,可以执行几乎任何你想让他们做的事,Quartz Scheduler包含很多企业级功能,例如支持JTA事务,集群等!
Quartz 可以为你做什么
如果你的应用有任务需要在给定的时间准时执行,或者你的系统有定期的维护工作,那么Quartz就是你的理想解决方案。
使用Quartz进行任务调度的实例:
-
租车过程:有人租车下了一个新的订单,安排2小时后用,到时,将系统将先确定订单状态,如果该订单还没收到过确认消息,则向他发出警告消息,并将订单状态改为等待干预。
-
系统维护:安排一个工作,每个工作日(节假日除外的所有平日)的11:30将数据库的内容放到一个XML文件中。
-
在应用中提供提醒服务。
Quartz 特征(Quartz Features)
运行环境(Runtime Environments)
- Quartz可以在另一个自由独立的应用程序中运行
- Quartz可以在一个应用服务器中(或者servlet容器中)被实例化,并参与事务处理
- Quartz可以作为一个独立的的程序(自己的java虚拟机内)运行,被远程接口调用。
- Quartz可以被实例化为一组独立的程序(拥有负载均衡和故障转移能力)来执行工作。
任务调度(Job Scheduling)
当一个给定的触发器(Trigger)触发时,任务(Job)将执行。触发器可以被下列指令的任何组合所创建:
- 一天中的某个特定时间(到毫秒)
- 一周中的特定几天
- 一个月中的特定几天
- 一年中的特定几天
- 日历中非特定的几天(例如商务假期)
- 重复特定次数
- 重复直到某个特定时间
- 无限的重复
- 在特定间隔后重复
任务(Job)可以被命名并被放置于一个组(Group)中,触发器(Trigger)也可以被命名并被放入一个组(Group)中,这样可以在调度器(scheduler)中很好的的组织安排它们。
一个任务(Job)只能被调度器(scheduler)添加一次,但是可以注册在多个触发器(Trigger)中。
在企业级的Java环境中,任务(Job)可以作为分布式事务的一部分执行它们的工作
任务执行(Job Execution)
- 任务(Job)可以是任何实现简单Job接口的Java类,你的类可以执行其他任何操作
- 任务(Job)类的实例可以被Quartz实例化,也可以被应用的框架实例化
- 当一个触发器(Trigger)触发时,调度器(Scheduler)程序将通知实现了JobListener和TriggerListener接口的Java对象(监听器可以是简单的Java对象, 或者EJBs, 或者JMS publishers, etc)。这些监听器在任务(Job)执行完后,也会收到通知
- 当任务(Job)完成时, 他们返回JobCompletionCode (告知调度程序失败或者成功)。JobCompletionCode 还可以指示调度程序(Scheduler)基于成功或者失败执行操作,例如立即重新执行任务(Job)
任务持久化(Job Persistence)
- Quartz的设计包括一个JobStore接口的实现,可以提供任务(Job)存储的多种机制。
- 当使用了JDBCJobStore, 所有被配置为非易失的任务(Job)和触发器(Trigger)将通过JDBC存储在关系数据库中
- 当使用了RAMJobStore, 所有的任务(Job)和触发器(Trigger)被存储在RAM中,因此在程序执行时,并不具有持久性,但这不需要外部数据库
事务(Transactions)
- Quartz可以可以通过使用JobStoreCMT(JDBCJobStore的一个子类),参与JTA事务
- 在执行任务(Job)时,Quartz可以管理JTA事务(启动和调用),以便被任务执行的工作在JTA事务中自动执行了。
集群特征(Cluster)
- 提供故障切换
- 提供负载均衡
- Quartz的内置集群特征依赖数据库持久化(通过JDBCJobStore)
- Terracotta ,Quartz的拓展,提供不需要后端数据库支持的集群功能
监听器&&插件
- 应用(Application)通过继承listener接口捕获调度事件,来监控或者控制Job/Trigger
- 插件机制可以被用来给Quartz添加功能, 例如保存任务执行的记录,从文件中加载Job/Trigger的定义
- Quartz可以装载大量的已完成的监听器和插件
配置Quartz Scheduler
一个简单的 quartz.properties 文件
org.quartz.scheduler.instanceName = MyScheduler //Scheduler 名字
org.quartz.threadPool.threadCount = 3 //线程池大小,最多3个Job同时执行
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore //数据存储方式
开始一个简单的应用
一个简单的开始关闭的实例
HelloJob.java
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
/**
* Created by zj.fan on 2016/3/1.
*/
public class HelloJob implements Job {
public static final Logger _log = LoggerFactory.getLogger(HelloJob.class);
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
_log.info("Hello World! - " + new Date() + "-" + jobExecutionContext.getJobDetail().getJobDataMap().get("key1"));
}
}
SimpleExample.java
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
/**
* 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 static final Logger log = LoggerFactory.getLogger(SimpleExample.class);
public void run() throws Exception {
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 = DateBuilder.evenMinuteDate(new Date());
log.info("------- Scheduling Job -------------------");
// define the job and tie it to our example1.HelloJob class
JobDataMap dataMap = new JobDataMap();
dataMap.put("key1", "value1");
JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").usingJobData(dataMap).build();
// Trigger the job to run on the next round minute
Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();
// 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 65 seconds... -------------");
try {
// wait 65 seconds to show job
Thread.sleep(65L * 1000L);
// executing...
} catch (Exception e) {
//
}
// 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();
}
}
需要添加log4j.properties
log4j.rootLogger=DEBUG,console,logFile
log4j.additivity.org.apache=true
# 控制台(console)
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.ImmediateFlush=true
log4j.appender.console.Target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 日志文件(logFile)
log4j.appender.logFile=org.apache.log4j.FileAppender
log4j.appender.logFile.Threshold=DEBUG
log4j.appender.logFile.ImmediateFlush=true
log4j.appender.logFile.Append=true
log4j.appender.logFile.File=E:/logs/log.log4j
log4j.appender.logFile.layout=org.apache.log4j.PatternLayout
log4j.appender.logFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
运行结果
[INFO ] 2016-03-11 17:44:25,686(0) --> [main] example1.SimpleExample.run(SimpleExample.java:40): ------- Initializing ----------------------
[INFO ] 2016-03-11 17:44:25,810(124) --> [main] org.quartz.impl.StdSchedulerFactory.instantiate(StdSchedulerFactory.java:1172): Using default implementation for ThreadExecutor
[INFO ] 2016-03-11 17:44:25,817(131) --> [main] org.quartz.simpl.SimpleThreadPool.initialize(SimpleThreadPool.java:268): Job execution threads will use class loader of thread: main
[INFO ] 2016-03-11 17:44:25,881(195) --> [main] org.quartz.core.SchedulerSignalerImpl.<init>(SchedulerSignalerImpl.java:61): Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
[INFO ] 2016-03-11 17:44:25,881(195) --> [main] org.quartz.core.QuartzScheduler.<init>(QuartzScheduler.java:240): Quartz Scheduler v.2.2.2 created.
[INFO ] 2016-03-11 17:44:25,893(207) --> [main] org.quartz.simpl.RAMJobStore.initialize(RAMJobStore.java:155): RAMJobStore initialized.
[INFO ] 2016-03-11 17:44:25,895(209) --> [main] org.quartz.core.QuartzScheduler.initialize(QuartzScheduler.java:305): Scheduler meta-data: Quartz Scheduler (v2.2.2) '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 ] 2016-03-11 17:44:25,895(209) --> [main] org.quartz.impl.StdSchedulerFactory.instantiate(StdSchedulerFactory.java:1327): Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
[INFO ] 2016-03-11 17:44:25,895(209) --> [main] org.quartz.impl.StdSchedulerFactory.instantiate(StdSchedulerFactory.java:1331): Quartz scheduler version: 2.2.2
[INFO ] 2016-03-11 17:44:25,895(209) --> [main] example1.SimpleExample.run(SimpleExample.java:46): ------- Initialization Complete -----------
[INFO ] 2016-03-11 17:44:25,897(211) --> [main] example1.SimpleExample.run(SimpleExample.java:51): ------- Scheduling Job -------------------
[INFO ] 2016-03-11 17:44:25,951(265) --> [main] example1.SimpleExample.run(SimpleExample.java:63): group1.job1 will run at: Fri Mar 11 17:45:00 CST 2016
[INFO ] 2016-03-11 17:44:25,951(265) --> [main] org.quartz.core.QuartzScheduler.start(QuartzScheduler.java:575): Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
[DEBUG] 2016-03-11 17:44:25,952(266) --> [DefaultQuartzScheduler_QuartzSchedulerThread] org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:276): batch acquisition of 0 triggers
[INFO ] 2016-03-11 17:44:25,952(266) --> [main] example1.SimpleExample.run(SimpleExample.java:69): ------- Started Scheduler -----------------
[INFO ] 2016-03-11 17:44:25,952(266) --> [main] example1.SimpleExample.run(SimpleExample.java:73): ------- Waiting 65 seconds... -------------
[DEBUG] 2016-03-11 17:44:49,376(23690) --> [DefaultQuartzScheduler_QuartzSchedulerThread] org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:276): batch acquisition of 1 triggers
[DEBUG] 2016-03-11 17:45:00,004(34318) --> [DefaultQuartzScheduler_QuartzSchedulerThread] org.quartz.simpl.SimpleJobFactory.newJob(SimpleJobFactory.java:51): Producing instance of Job 'group1.job1', class=example1.HelloJob
[DEBUG] 2016-03-11 17:45:00,007(34321) --> [DefaultQuartzScheduler_QuartzSchedulerThread] org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:276): batch acquisition of 0 triggers
[DEBUG] 2016-03-11 17:45:00,007(34321) --> [DefaultQuartzScheduler_Worker-1] org.quartz.core.JobRunShell.run(JobRunShell.java:201): Calling execute on job group1.job1
[INFO ] 2016-03-11 17:45:00,007(34321) --> [DefaultQuartzScheduler_Worker-1] example1.HelloJob.execute(HelloJob.java:15): Hello World! - Fri Mar 11 17:45:00 CST 2016-value1
[DEBUG] 2016-03-11 17:45:25,844(60158) --> [DefaultQuartzScheduler_QuartzSchedulerThread] org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:276): batch acquisition of 0 triggers
[INFO ] 2016-03-11 17:45:30,955(65269) --> [main] example1.SimpleExample.run(SimpleExample.java:83): ------- Shutting Down ---------------------
[INFO ] 2016-03-11 17:45:30,956(65270) --> [main] org.quartz.core.QuartzScheduler.shutdown(QuartzScheduler.java:694): Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.
[INFO ] 2016-03-11 17:45:30,956(65270) --> [main] org.quartz.core.QuartzScheduler.standby(QuartzScheduler.java:613): Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.
[DEBUG] 2016-03-11 17:45:30,957(65271) --> [main] org.quartz.simpl.SimpleThreadPool.shutdown(SimpleThreadPool.java:328): Shutting down threadpool...
[DEBUG] 2016-03-11 17:45:31,010(65324) --> [DefaultQuartzScheduler_Worker-1] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,322(65636) --> [DefaultQuartzScheduler_Worker-2] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,322(65636) --> [DefaultQuartzScheduler_Worker-3] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,323(65637) --> [DefaultQuartzScheduler_Worker-7] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,323(65637) --> [DefaultQuartzScheduler_Worker-8] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,323(65637) --> [DefaultQuartzScheduler_Worker-9] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,323(65637) --> [DefaultQuartzScheduler_Worker-6] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,323(65637) --> [DefaultQuartzScheduler_Worker-10] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,323(65637) --> [DefaultQuartzScheduler_Worker-5] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,323(65637) --> [DefaultQuartzScheduler_Worker-4] org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:612): WorkerThread is shut down.
[DEBUG] 2016-03-11 17:45:31,324(65638) --> [main] org.quartz.simpl.SimpleThreadPool.shutdown(SimpleThreadPool.java:393): No executing jobs remaining, all threads stopped.
[DEBUG] 2016-03-11 17:45:31,325(65639) --> [main] org.quartz.simpl.SimpleThreadPool.shutdown(SimpleThreadPool.java:395): Shutdown of threadpool complete.
[INFO ] 2016-03-11 17:45:31,325(65639) --> [main] org.quartz.core.QuartzScheduler.shutdown(QuartzScheduler.java:771): Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.
[INFO ] 2016-03-11 17:45:31,325(65639) --> [main] example1.SimpleExample.run(SimpleExample.java:85): ------- Shutdown Complete -----------------