关闭

Quartz 使用(2.x版本)

1022人阅读 评论(0) 收藏 举报
分类:


Quartz 几个关键词简介:


Scheduler:调度交互的主要API,负责作业/任务调度。



Job :由scheduler负责调度的作业/任务 ,如果你想实现一个作业,需要实现此接口的execute方法。


JobDetail:用于定义Job的实例。


Trigger: 作业执行的触发器,用于定义作业调度如何触发。比如每一小时定时触发一次。


SchedulerListener:  调度器的监听器。

Triggerlistener:  触发器的监听器。

JobListener:   job的监听器。


ListenerManager:监听器管理类,用于添加,移除,设置监听器等。


比如scheduler.getListenerManager.addJobListener(JobListener joblistener,Matcher<JobKey> matcher);


Matcher:用于匹配监听器。

SchedulerFactory :scheduler构造器接口。有三个重要函数getScheduler(),getScheduler(String schedName),getAllSchedulers(),

                             已经实现了此构造器接口有:StdSchedulerFactory 和DirectSchedulerFactory , 此两个实现类,可由于产生scheduler调度器实例。


JobBuilder: Job生成的工具类,用于定义、构造JobDetail的实例。


TriggerBuilder“:Trrigger构造的工具类,用于定义、构造Trigger的实例。


DateBuilder: 日期工具类,可结合TriggerBuilder使用。


JobKey :  Job的识别键,封装jobName和jobGruopName

TriggerKey :  类似JobKey,Trigger的识别键,封装triggerName和triggerGruopName ,

                    比如使用getTrigger(TriggerKey key)取代1.x中的getTrigger(String name,String group).很多其他方法也是类似,JobKey也是如此。


英文描述如下:

The key interfaces of the Quartz API are:

  • Scheduler - the main API for interacting with the scheduler.
  • Job - an interface to be implemented by components that you wish to have executed by the scheduler.
  • JobDetail - used to define instances of Jobs.
  • Trigger - a component that defines the schedule upon which a given Job will be executed.
  • JobBuilder - used to define/build JobDetail instances, which define instances of Jobs.
  • TriggerBuilder - used to define/build Trigger instances.



一个例子:


定义个Job:


/**
 *
 *  Copyright (c) 2013, Seven. All rights reserved.
 *
 */
package com.seven.quartz.job;


import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;


/**
 * The class designed for ...
 * 
 *
 * @author  seven
 * @version 1.0
 * @date    2013-12-2  
 */
public class HelloJob implements Job{


	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		System.out.println("say hello ,i am a hello job!");
	}


}





测试类:


/**
 *
 *  Copyright (c) 2013, Seven. All rights reserved.
 *
 */
package com.seven.quartz.schedule;

import java.util.Properties;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.JobListener;
import org.quartz.Matcher;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.TriggerListener;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.KeyMatcher;

import com.seven.quartz.job.HelloJob;
import com.seven.quartz.listener.MyJobListener;

/**
 * The class designed for ...
 * 
 * 
 * @author seven
 * @version 1.0
 * @date 2013-12-3
 */
public class ScheduleTest {
	private static final Logger logger = Logger.getLogger(ScheduleTest.class);
	private Scheduler scheduler = null;

	public Scheduler init() {
		if (scheduler == null) {
			try {
				scheduler = StdSchedulerFactory.getDefaultScheduler();
				// 此处修改修改可以设置监听器,以下几个方法没有指定matcher,那么都是全局的,针对所有的
				// scheduler.getListenerManager().addJobListener(new
				// MonitorJobListener());
				// scheduler.getListenerManager().addSchedulerListener(new
				// MonitorSchedulerListener());
				// scheduler.getListenerManager().addTriggerListener(new
				// MonitorTriggerListener());
			} catch (SchedulerException e) {
				logger.error(
						"failder to builder scheduler , the error message is:",
						e);
			}
		}

		return scheduler;
	}

	/**
	 * 此方法可以设置quartz属性,比如misfire,threadCount等属性
	 * 
	 * @return
	 */
	public Scheduler getScheduler(Properties props) {

		if (scheduler == null) {
			try {
			   /* props = new Properties();
				props.put(StdSchedulerFactory.PROP_THREAD_POOL_CLASS,
						"org.quartz.simpl.SimpleThreadPool");
				// quartz的线程数,同时运行的线程数
				props.put("org.quartz.threadPool.threadCount", "8");
				// trigger过期1小时内还有效
				props.put("org.quartz.jobStore.misfireThreshold", "60*60*1000");
				*/
				StdSchedulerFactory factory = new StdSchedulerFactory();
				factory.initialize(props);
				scheduler = factory.getScheduler();
			} catch (SchedulerException e) {
				logger.error("can't get a scheduler !", e);
			}
		}

		return scheduler;
	}
	
	public void addJobListener(JobKey jobKey,JobListener jobListener)throws SchedulerException{
		Matcher<JobKey> matcher =  KeyMatcher.keyEquals(jobKey);

		try {
			this.scheduler.getListenerManager().addJobListener(jobListener, matcher);
		} catch (SchedulerException e) {
			try {
				logger.error("add listener ["+jobListener.getName()+"] to "+scheduler.getSchedulerName()+"scheduler error", e);
			} catch (SchedulerException e1) {
				logger.error("get scheduler name error ", e1);
			}
			throw e;
		}
	}
	
	public void addTriggerListener(TriggerKey triggerkey,TriggerListener triggerListener)throws SchedulerException{
		Matcher<TriggerKey> matcher =  KeyMatcher.keyEquals(triggerkey);

		try {
			this.scheduler.getListenerManager().addTriggerListener(triggerListener, matcher);
		} catch (SchedulerException e) {
			try {
				logger.error("add listener ["+triggerListener.getName()+"] to "+scheduler.getSchedulerName()+"scheduler error", e);
			} catch (SchedulerException e1) {
				logger.error("get scheduler name error ", e1);
			}
			throw e;
		}
	}

	public void scheduleJob(String jobName, String triggerName,
			String cronExpression, Class<? extends Job> jobClass) {
		JobDetail jobDetail = null;
		CronTrigger trigger = null;
		JobKey jobKey = new JobKey(jobName, "myJobGroup");
		TriggerKey triggerKey = new TriggerKey(triggerName, "myTriggerGroup");

		jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobKey).build();

		trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
				.forJob(jobDetail)
				.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
				.build();
		try {
			 this.scheduler.scheduleJob(jobDetail, trigger);
		} catch (SchedulerException e) {
			logger.error("can't scheduleJob !", e);
		}

	}

	public void scheduleJob(JobKey jobKey, TriggerKey triggerKey,
			String cronExpression, Class<? extends Job> jobClass) {
		JobDetail jobDetail = null;
		CronTrigger trigger = null;
		jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobKey).build();
		trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
				.forJob(jobDetail)
				.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
				.build();
		try {
			 this.scheduler.scheduleJob(jobDetail, trigger);
		} catch (SchedulerException e) {
			logger.error("can't scheduleJob !", e);
		}

	}

	/**
	 * 设置立刻生成
	 * 
	 * @param jobKey
	 * @param jobClass
	 */
	public void triggerJobNow(JobKey jobKey, Class<? extends Job> jobClass) {
		JobDetail jobDetail = null;
		jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobKey)
				.storeDurably(true).build();
		try {
			this.scheduler.addJob(jobDetail, true);
		} catch (SchedulerException e) {
			logger.error("can't add Job !", e);
		}
		try {
			this.scheduler.triggerJob(jobKey);
		} catch (SchedulerException e) {
			logger.error("can't trigger Job !", e);
		}

	}

	public void start() {
		try {
			this.scheduler.start();
		} catch (SchedulerException e) {
			logger.error("can't scheduleJob !", e);
		}
	}

	public static void main(String[] args) {
		ScheduleTest test = new ScheduleTest();
		JobKey jobKey = new JobKey("myJob", "myJobGroup");
		test.init();
		try {
			test.addJobListener(jobKey, new MyJobListener());
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		test.triggerJobNow(jobKey, HelloJob.class);
		test.start();

		// TriggerKey triggerKey = new TriggerKey("myTrigger",
		// "myTriggerGroup");
		// //每隔10S执行一次
		// String cronExpression = "0/10 * * * * ?";
		// test.init();
		// test.scheduleJob(jobKey, triggerKey, cronExpression, HelloJob.class);
		// test.start();
	}

}





JobBuilder、TriggerBuilder 这两个工具类设计的很不错。使用了build方式,Effective Java中也有提到。


JobBuilder 中的newJob(Class <? extends Job> jobclass)方法泛型用的很好。值得学习。


在线生成Cron表达式的一个工具:http://www.cronmaker.com/



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:234478次
    • 积分:3078
    • 等级:
    • 排名:第11255名
    • 原创:52篇
    • 转载:102篇
    • 译文:0篇
    • 评论:19条
    最新评论