2010-11-03 quartz学习笔记一

Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that are programmed to fulfill the requirements of your application. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering. You can download the most recent stable version at  http://quartz-scheduler.org/overview/index.html.

      Quartz是一个开源的任务调度服务,可以同时运行成百上千个简单或者复杂的任务。

一.搭建Quart运行环境

    下载最新版本,解压后将lib目录下所有jar包加入你工程classpath下,注意jar包的冲突问题。将跟目录下的quartz-all-***.jar加入classpath,其中xxx为版本号。

二.最简单的helloWorld

   (1) 引入所需要的类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

   (2)获取一个Scheduler

 // 使用工厂模式
SchedulerFactory sf = new StdSchedulerFactory(); 
Scheduler sched = sf.getScheduler();

  (3) 声明一个任务和1个触发器

 

        // computer a time that is on the next round minute
        Date runTime = TriggerUtils.getEvenMinuteDate(new Date());
        // define the job and tie it to our HelloJob class
        JobDetail job = new JobDetail("job1", "group1", HelloJob.class);
        // Trigger the job to run on the next round minute
        SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1", runTime);

 (4)将任务和触发器进行关联

 

   // Tell quartz to schedule the job using our trigger 
 sched.scheduleJob(job, trigger);

 (5)启动调度器

 

       // Start up the scheduler (nothing can actually run until the 
        // scheduler has been started)
        sched.start();

 (6)执行完任务后关闭调度器

 

     // shut down the scheduler
    /// 如果不关闭调度器,则程序会一直执行下去,因为一直有个调度器的线程在执行
        log.info("------- Shutting Down ---------------------");
        sched.shutdown(true);
        log.info("------- Shutdown Complete -----------------");

 (7)自定义的任务类HelloJob

 

public class HelloJob implements Job 

 (8)实现Excute方法

 

   public void execute(JobExecutionContext context)
        throws JobExecutionException {

        // Say Hello to the World and display the date/time
        System.out.println("Hello World! - " + new Date());
    }

 (9)执行结果

 

Hello World! - Wed Nov 03 11:40:00 CST 2010
 

 

你可能感兴趣的:(html,quartz,UP)