`

Java定时器Quartz初体验

    博客分类:
  • J2EE
阅读更多
Quartz 官网 http://quartz-scheduler.org
Quartz各版本下载地址http://quartz-scheduler.org/downloads/catalog
Quartz官方文档地址http://www.quartz-scheduler.org/documentation
Release Notes:
Quartz 2.0.2, 5/27/2011
Quartz 1.8.5, 4/12/2011
Quartz 1.7.3, 2/23/2010
Quartz 1.6.6, 11/2/2009
Quartz 1.5.2, 3/3/2006
Quartz 1.4.5, 3/13/2005
搜了一下网络上的很多有关Quartz的中文版的东西还都是1.6版本前的,看来近两年大家使用Quartz的不多啊。但是项目需求需要我学习一下,还是用最新的2.0.2吧。
包里面有15个例子,我慢慢看吧,估计这十五个例子看完就基本掌握了Quartz了吧。

按照官方的Quick Start:http://www.quartz-scheduler.org/documentation/quartz-2.1.x/quick-start
首先看看quartz.properties的配置文件吧,不过貌似只有例10,11,14用了。
org.quartz.scheduler.instanceName: PriorityExampleScheduler

# Set thread count to 1 to force Triggers scheduled for the same time to 
# to be ordered by priority.
org.quartz.threadPool.threadCount: 1
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool

org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore


先上一个例1吧:
Job类,你要执行的Job
package com.oneregal.util;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * @author yiranrenxiaoyao
 */
public class HelloJob implements Job {

    private static Logger _log = LoggerFactory.getLogger(HelloJob.class);

    public HelloJob() {
    }

    /**
     * 
     * @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());

        JobKey jobKey = context.getJobDetail().getKey();
		JobDataMap dataMap = context.getJobDetail().getJobDataMap();
		
		String jobSays = dataMap.getString("jobSays");
		float myFloatValue = dataMap.getFloat("myFloatValue");
        System.out.println("JobSays:" + jobSays);
    }

}

真正的定时器在这里:
package com.oneregal.util;

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;

/**
 * @author yiranrenxiaoyao
 */
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
//You will typically want to use a static import of all of its methods, 
//in order to have the DSL-feel within your code.
//以上是官方文档里面的解释为什么用import static,可以让你DSL-feel,
//这feel其实我觉得到不太习惯呢,还是更喜欢JobBuilder.newJob(HelloJob.class)
        JobDetail job = newJob(HelloJob.class)
            .withIdentity("job1", "group1")
            .usingJobData("jobSays", "Hello Quartz!")
            .usingJobData("myFloatValue", 3.1415926f)
            .build();
//Tutorials里面有.usingJobData("myStateData", new ArrayList()),可是我看API里面
//Value属性只有Boolean,Double,Float,Integer,Long,没看到Object或者List
//但是usingJobData(JobDataMap)这个就实用多了,类似Java的Map可以随意往里面塞数据了
//JobDataMap dMap = new JobDataMap();dMap.put(key,value);

        // 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();

    }

}

新老版本的改动还是挺大的
JobDetail jobDetail = new JobDetail("jobDetail-s1", "jobDetailGroup-s1", HelloJob.class);
新版本的JobDetail也改为接口类型了。
JobDetail job = newJob(HelloJob.class)
            .withIdentity("job1", "group1")
            .build();
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics