Quartz 任务调度:初体验
 
Quartz 是个开源的作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。Quartz框架包含了调度器监听、作业和触发器监听。你可以配置作业和触发器监听为全局监听或者是特定于作业和触发器的监听。Quartz 允许开发人员根据时间间隔(或天)来调度作业。它实现了作业和触发器的多对多关系,还能把多个作业与不同的触发器关联。整合了 Quartz 的应用程序可以重用来自不同事件的作业,还可以为一个事件组合多个作业。Quartz在功能上远远超越了JDK自带的Timer,很好很强大!
 
相关网站:
 
下面是官方的一个入门例子,我做了部分改动,添加上了中文注释,主要是了解Quartz 的工作方式和试用方法。
 
package org.quartz.examples.example1;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerUtils;
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 {
        Log log = LogFactory.getLog(SimpleExample.class);

        log.info("------- 初始化开始 ----------------------");
        // 首先创建一个调度程序工厂
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        // 从工厂获取一个调度程序实例
        Scheduler scheduler = schedulerFactory.getScheduler();
        log.info("------- 初始化完成 -----------");

        log.info("------- 调度任务 -------------------");

        // 设置作业调度时间:某一时间后的下一秒
        Date runTime = TriggerUtils.getEvenMinuteDate(new Date());

        // 定义一个具体作业job1,并加入group1组,并且绑定到具体的作业类HelloJob上
        JobDetail jobDetail = new JobDetail("job1", "group1", HelloJob.class);

        // 创建一个简单的触发器
        SimpleTrigger simpleTrigger = new SimpleTrigger("trigger1", "group1");
        // 设置触发时间
        simpleTrigger.setStartTime(runTime);
        // 设置重复执行周期
        simpleTrigger.setRepeatInterval(2000);
        // 设置重复执行次数
        simpleTrigger.setRepeatCount(3);


        // 设置调度的具体作业和相关的触发器
        scheduler.scheduleJob(jobDetail, simpleTrigger);
        log.info(jobDetail.getFullName() + " 将在某时刻: " + runTime +" 运行!");

        // 启动调度程序
        scheduler.start();
        log.info("------- 已启动调度程序 -----------------");

        // wait long enough so that the scheduler as an opportunity to  
        // run the job!
        log.info("------- 等待15秒... -------------");
        try {
            // 等待15秒显示
            Thread.sleep(15L * 1000L);
            // 执行......
        } catch (Exception e) {
        }

        // 关闭调度程序
        log.info("------- 关闭调度程序开始 ---------------------");
        scheduler.shutdown(true);
        log.info("------- 关闭调度程序完成 -----------------");
    }

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

        SimpleExample example = new SimpleExample();
        example.run();

    }
}
 
package org.quartz.examples.example1;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;

/**
* <p>
* This is just a simple job that says "Hello" to the world.
* 一个简单的作业,来自Quartz的Simple Examples。
* </p>
*
* @author Bill Kratzer
*/

public class HelloJob implements Job {

    private static Log _log = LogFactory.getLog(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());
    }
}
 
运行结果:
2008-08-21 00:01:06  - INFO  org.quartz.examples.example1.SimpleExample     - ------- 初始化开始 ----------------------
2008-08-21 00:01:07  - INFO  org.quartz.simpl.SimpleThreadPool     - Job execution threads will use class loader of thread: main
2008-08-21 00:01:07  - INFO  org.quartz.core.QuartzScheduler     - Quartz Scheduler v.1.6.0 created.
2008-08-21 00:01:07  - INFO  org.quartz.simpl.RAMJobStore     - RAMJobStore initialized.
2008-08-21 00:01:07  - INFO  org.quartz.impl.StdSchedulerFactory     - Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
2008-08-21 00:01:07  - INFO  org.quartz.impl.StdSchedulerFactory     - Quartz scheduler version: 1.6.0
2008-08-21 00:01:07  - INFO  org.quartz.examples.example1.SimpleExample     - ------- 初始化完成 -----------
2008-08-21 00:01:07  - INFO  org.quartz.examples.example1.SimpleExample     - ------- 调度任务 -------------------
2008-08-21 00:01:07  - INFO  org.quartz.examples.example1.SimpleExample     - group1.job1 将在某时刻: Thu Aug 21 00:02:00 CST 2008 运行!
2008-08-21 00:01:07  - INFO  org.quartz.core.QuartzScheduler     - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
2008-08-21 00:01:07  - INFO  org.quartz.examples.example1.SimpleExample     - ------- 已启动调度程序 -----------------
2008-08-21 00:01:07  - INFO  org.quartz.examples.example1.SimpleExample     - ------- 等待15秒... -------------
2008-08-21 00:01:09  - INFO  org.quartz.examples.example1.SimpleExample     - ------- 关闭调度程序开始 ---------------------
2008-08-21 00:01:09  - INFO  org.quartz.core.QuartzScheduler     - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.
2008-08-21 00:01:09  - INFO  org.quartz.core.QuartzScheduler     - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.
2008-08-21 00:01:09  - INFO  org.quartz.simpl.SimpleThreadPool     - There are still 13 worker threads active. See javadoc runInThread(Runnable) for a possible explanation
2008-08-21 00:01:09  - INFO  org.quartz.core.QuartzScheduler     - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.
2008-08-21 00:01:09  - INFO  org.quartz.examples.example1.SimpleExample     - ------- 关闭调度程序完成 -----------------

Process finished with exit code 0
 
注意:这个示例依赖jta.jar,还没仔细研究为什么要依赖这个包,不过这个包就在Quartz的发布包中,目前最新的releas版是1.60.