标签:
1.Quartz 是用来完成任务调度的。
2.Quartz 的三个核心概念:调度器、任务、触发器。
(1)Job:通过实现该接口来定义需要执行的任务。
public interface Job { /** * Called by the <code>{@link Scheduler}</code> when a <code>{@link Trigger}</code> fires that is associated with the <code>Job</code>. */ void execute(JobExecutionContext context) throws JobExecutionException;
}
(2)JobDetail:Quartz 在每次执行 Job 时,都重新创建一个 Job 实例,所以它不是直接接受一个 Job 的实例,而是接受 Job 的一个实现类,以便运行时通过反射区实例化 Job。
JobDtail 就是用来描述 Job 的实现类以及其他相关的静态信息。
package org.quartz; import java.io.Serializable; /** * Conveys the detail properties of a given <code>Job</code> instance. JobDetails are * to be created/defined with {@link JobBuilder}. * * <p> * Quartz does not store an actual instance of a <code>Job</code> class, but * instead allows you to define an instance of one, through the use of a <code>JobDetail</code>. * </p> * * <p> * <code>Job</code>s have a name and group associated with them, which * should uniquely identify them within a single <code>{@link Scheduler}</code>. * </p> * * <p> * <code>Trigger</code>s are the ‘mechanism‘ by which <code>Job</code>s * are scheduled. Many <code>Trigger</code>s can point to the same <code>Job</code>, * but a single <code>Trigger</code> can only point to one <code>Job</code>. * </p>*/ public interface JobDetail extends Serializable, Cloneable { public JobKey getKey(); public String getDescription(); public Class<? extends Job> getJobClass(); public JobDataMap getJobDataMap(); public boolean isDurable(); public boolean isPersistJobDataAfterExecution(); public boolean isConcurrentExectionDisallowed(); public boolean requestsRecovery(); public Object clone(); public JobBuilder getJobBuilder(); }
(3)Trigger(中文"触发"的意思):描述出发 Job 执行的时间触发规则。
package org.quartz; import java.io.Serializable; import java.util.Comparator; import java.util.Date; import org.quartz.JobDataMap; import org.quartz.JobKey; import org.quartz.ScheduleBuilder; import org.quartz.TriggerBuilder; import org.quartz.TriggerKey; /** * The base interface with properties common to all <code>Trigger</code>s - * use {@link TriggerBuilder} to instantiate an actual Trigger. * * <p> * <code>Triggers</code>s have a {@link TriggerKey} associated with them, which * should uniquely identify them within a single <code>{@link Scheduler}</code>. * </p> * * <p> * <code>Trigger</code>s are the ‘mechanism‘ by which <code>Job</code>s * are scheduled. Many <code>Trigger</code>s can point to the same <code>Job</code>, * but a single <code>Trigger</code> can only point to one <code>Job</code>. * </p> * * <p> * Triggers can ‘send‘ parameters/data to <code>Job</code>s by placing contents * into the <code>JobDataMap</code> on the <code>Trigger</code>. * </p> * * @see TriggerBuilder * @see JobDataMap * @see JobExecutionContext * @see TriggerUtils * @see SimpleTrigger * @see CronTrigger * @see CalendarIntervalTrigger * * @author James House */ public interface Trigger extends Serializable, Cloneable, Comparable<Trigger> { long serialVersionUID = -3904243490805975570L; int MISFIRE_INSTRUCTION_SMART_POLICY = 0; int MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY = -1; int DEFAULT_PRIORITY = 5; TriggerKey getKey(); JobKey getJobKey(); String getDescription(); String getCalendarName(); JobDataMap getJobDataMap(); int getPriority(); boolean mayFireAgain(); Date getStartTime(); Date getEndTime(); Date getNextFireTime(); Date getPreviousFireTime(); Date getFireTimeAfter(Date var1); Date getFinalFireTime(); int getMisfireInstruction(); TriggerBuilder<? extends Trigger> getTriggerBuilder(); ScheduleBuilder<? extends Trigger> getScheduleBuilder(); boolean equals(Object var1); int compareTo(Trigger var1); public static class TriggerTimeComparator implements Comparator<Trigger>, Serializable { private static final long serialVersionUID = -3904243490805975570L; public TriggerTimeComparator() { } public static int compare(Date nextFireTime1, int priority1, TriggerKey key1, Date nextFireTime2, int priority2, TriggerKey key2) { if(nextFireTime1 != null || nextFireTime2 != null) { if(nextFireTime1 == null) { return 1; } if(nextFireTime2 == null) { return -1; } if(nextFireTime1.before(nextFireTime2)) { return -1; } if(nextFireTime1.after(nextFireTime2)) { return 1; } } int comp = priority2 - priority1; return comp != 0?comp:key1.compareTo(key2); } public int compare(Trigger t1, Trigger t2) { return compare(t1.getNextFireTime(), t1.getPriority(), t1.getKey(), t2.getNextFireTime(), t2.getPriority(), t2.getKey()); } } public static enum CompletedExecutionInstruction { NOOP, RE_EXECUTE_JOB, SET_TRIGGER_COMPLETE, DELETE_TRIGGER, SET_ALL_JOB_TRIGGERS_COMPLETE, SET_TRIGGER_ERROR, SET_ALL_JOB_TRIGGERS_ERROR; private CompletedExecutionInstruction() { } } public static enum TriggerState { NONE, NORMAL, PAUSED, COMPLETE, ERROR, BLOCKED; private TriggerState() { } } }
主要有两个实现类:
(4)Calendar:一些日历特定时间点的集合。一个 Trigger 可以和多个 Calendar 关联,以便包含或排除某些时间点。
(5)Scheduler:一个 Quartz 的独立运行容器,Trigger 和 JobDtail 可以注册到 Scheduler 中。
Scheduler 可以将 Trigger 绑定到某一个 JobDetail 中,这样当 Trigger 被触发时,对应的 Job 就被执行。
一个 Job 可以有多个对应的 Trigger ,但是一个 Trigger 只能对应一个 Job。
3. HelloWorld
(1)步骤:
(2)SimpleTrigger
/** * @author solverpeng * @create 2016-09-25-14:56 */ public class HelloWorld { public static void main(String[] args) throws SchedulerException, ParseException { JobDetailImpl jobDetail = new JobDetailImpl(); jobDetail.setGroup("test-group"); jobDetail.setName("test-name"); jobDetail.setJobClass(MyJob.class); SimpleTriggerImpl trigger = new SimpleTriggerImpl(); trigger.setName("test-trigger-name"); trigger.setGroup("test-trigger-group"); trigger.setStartTime(new Date()); trigger.setRepeatCount(5); trigger.setRepeatInterval(1000*5); SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); } }
(3)CronTrigger
Cron 表达式1:
Cron 表达式2:
Cron表达式示例
例子:
/** * @author solverpeng * @create 2016-09-25-14:56 */ public class HelloWorld { public static void main(String[] args) throws SchedulerException, ParseException { JobDetailImpl jobDetail = new JobDetailImpl(); jobDetail.setGroup("test-group"); jobDetail.setName("test-name"); jobDetail.setJobClass(MyJob.class); CronTriggerImpl trigger = new CronTriggerImpl(); trigger.setCronExpression("0/5 56 15 ? 9 SUN"); trigger.setStartTime(new Date()); trigger.setName("test-trigger-name"); trigger.setGroup("test-trigger-group"); SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); } }
官方 Demo:
package com.nucsoft.quartz; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import static org.quartz.JobBuilder.newJob; import static org.quartz.SimpleScheduleBuilder.simpleSchedule; import static org.quartz.TriggerBuilder.newTrigger; /** * @author solverpeng * @create 2016-09-25-16:49 */ public class HelloWorld { public static void main(String[] args) throws SchedulerException { // define the job and tie it to our MyJob class JobDetail job = newJob(MyJob.class).withIdentity("job1", "group1").build(); // Trigger the job to run now, and then repeat every 40 seconds Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startNow().withSchedule( simpleSchedule().withIntervalInSeconds(40).repeatForever()).build(); // Grab the Scheduler instance from the Factory Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // Tell quartz to schedule the job using our trigger scheduler.scheduleJob(job, trigger); // and start it off scheduler.start(); } }
4.总结
介绍了Quartz的几个核心概念,Cron 表达式,以及 Quartz 的 HelloWorld。Job 是用来定义要完成的任务,JobDetail用来描述它,Trigger 是一个触发器,用于触发任务,它们统一由 Scheduler
来管理。其中需要注意一点的是,国外每个星期的开始是从 星期日开始的,所以 6 表示星期五。
标签:
原文地址:http://www.cnblogs.com/solverpeng/p/5906229.html