Quartz 是一个功能强大的作业调度工具。
日程安排好了之后,我们就要去执行,Quartz可以计划的执行这些任务,定时、循环或在某一个时间来执行我们需要做的事,用到Quartz可以很好的解决我们平时工作中的琐碎麻烦的事:比如,数据库系统需要我们每天23:50的时候需要执行一次备份,每月的15号需要将公司账目平台里的工资表导出……有了Quartz可以很好的来解决这些问题,不需要我们手动来执行。
Quartz官网:http://quartz-scheduler.org/ 可以在这里下载Quartz,也可以到我共享的资源里下载,免分的,请点击这里-》http://down.51cto.com/data/426993
我下载的是当前最新版本quartz-2.1.5。下载后,我们的压缩包里有:
docs文件夹:里面是Quartz的API、表数据库、图片文件夹
examples:里面是官方提供的一些DEMO
lib:第三方库,一些特性需要它们依靠
quartz:源码
quartz-*:支持各框架的源码
*.jar:一些JAR包
……
下面我们可以将官网下载的安装包里提供的例子导入到自己的IDE中,我使用的是MyEclipse8.5+Apache Tomcat6.0+JDK1.6.0。
创建一个Web应用程序,将第三方库lib文件夹下的jar包(quartz依赖的包)以及quartz-all-2.1.5.jar拷贝到WEB-INF/lib下,把examples/src文件夹拷贝到你的项目src下,刷新下项目,可能会出错,解决办法看这篇[MyEclipse中一些有趣的快捷键]这样即完成示例的准备工作。
来看官网提供的第一个例子: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>
- * <p>
- * Quartz requires a public empty constructor so that the
- * scheduler can instantiate the class whenever it needs.
- * </p>
- */
- public HelloJob() {
- }
- /**
- * <p>
- * 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>.
- * </p>
- *
- * @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)
- .build();
- 告诉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.
- *
- */
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> * <p> * Quartz requires a public empty constructor so that the * scheduler can instantiate the class whenever it needs. * </p> */ public HelloJob() { } /** * <p> * 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>. * </p> * * @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) .build(); 告诉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. * */
- package org.quartz.examples.example1;
- import static org.quartz.JobBuilder.newJob;
- import static org.quartz.TriggerBuilder.newTrigger;
- import static org.quartz.DateBuilder.*;
- import java.util.Date;
- import org.quartz.JobDetail;
- import org.quartz.Scheduler;
- import org.quartz.SchedulerFactory;
- import org.quartz.Trigger;
- import org.quartz.impl.StdSchedulerFactory;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- /**
- * 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)
- .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 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("------- 重新开始程序... -------------");
- sched.start();
- // 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();
- }
- }
package org.quartz.examples.example1; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import static org.quartz.DateBuilder.*; import java.util.Date; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerFactory; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 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) .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 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("------- 重新开始程序... -------------"); sched.start(); // 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.
[INFO] 06 六月 09:29:07.125 下午 main [org.quartz.core.QuartzScheduler]
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'
[INFO] 06 六月 09:29:07.125 下午 main [org.quartz.impl.StdSchedulerFactory]
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.
[INFO] 06 六月 09:29:07.171 下午 main [org.quartz.examples.example1.SimpleExample]
------- Started Scheduler -----------------
[INFO] 06 六月 09:29:07.171 下午 main [org.quartz.examples.example1.SimpleExample]
------- 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]
Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
[INFO] 06 六月 09:29:27.171 下午 main [org.quartz.examples.example1.SimpleExample]
------- Shutting Down ---------------------
[INFO] 06 六月 09:29:27.171 下午 main [org.quartz.core.QuartzScheduler]
Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.
[INFO] 06 六月 09:29:27.171 下午 main [org.quartz.core.QuartzScheduler]
Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.
[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); 是为了给调度的程序有时间执行。
=======================================================================
以上属于个人观点,难免有错误,如发现错误请留言告之,我会订正的。