Quartz的基本用法
一 Quartz的简单介绍
Quartz 是 OpenSymphony 开源组织在任务调度领域的一个开源项目,完全基于 Java 实现,一个优秀的开源调度框架,其特点是:强大的调度能力.灵活的应用方式,分布式和集群的能. 官网:http://www.quartz-scheduler.org
Quartz的核心元素
- Scheduler:任务调度器,是实际执行任务调度的控制器
- Trigger:触发器,用于定义任务调度的时间规则,有SimpleTrigger,CronTrigger等,其中SimpleTrigger定义时间规则简单的任务,CronTrigger通过设置Cron表达式定义复杂时间规则的任务
- JobDetail:用来描述Job实现类及其它相关的静态信息,如Job/Group名字、关联监听器等信息
- Job是一个接口,只有一个方法void execute(JobExecutionContext context),自定义任务只需要实现该方法即可
二 简单使用
- 新建一个Maven项目,新建完成后,修改pom.xml文件,添加Quartz依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
- 新建Job1,Job2两个类,两个类都实现Job接口,并实现executef方法
package quartzDemo.quartz;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
public class Job1 implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
JobKey jobKey = context.getJobDetail().getKey();
System.out.println(
String.format("%s: JobGroup:%s JobName:%s", DateTimeHelper.Now(), jobKey.getGroup(), jobKey.getName()));
JobDataMap dataMap = context.getMergedJobDataMap();
//
// String jobData = dataMap.getString("JobDetailData");
// String triggerData = dataMap.getString("TriggerData");
//
// System.out.println(String.format("JobDataMap: jobData:%s triggerData:%s", jobData, triggerData));
}
}
package quartzDemo.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
public class Job2 implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException {
JobKey jobKey = context.getJobDetail().getKey();
System.out.println(
String.format("%s: JobGroup:%s JobName:%s", DateTimeHelper.Now(), jobKey.getGroup(), jobKey.getName()));
}
}
- 在App.java中新建两个方法,分别初始化job1和job2,并且在main方法中将两个job添加到Scheduler,如下
package quartzDemo.quartz;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
/**
* @author QIUYANJUN
*/
public class App {
public static void main(String[] args) {
String job2cronExpression = "0/5 * * * * ? ";
JobModel job1 = InitSimpleJob();
JobModel job2 = InitCronJob(job2cronExpression);
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler;
try {
scheduler = factory.getScheduler();
scheduler.start();
scheduler.scheduleJob(job1.getJobDetail(), job1.getTrigger());
scheduler.scheduleJob(job2.getJobDetail(), job2.getTrigger());
System.out.println(DateTimeHelper.Now());
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* SimpleJob初始化
* @return
*/
private static JobModel InitSimpleJob() {
JobKey jobKey = JobKey.jobKey("job1", "group1");
JobDetail jobDetail = JobBuilder.newJob(Job1.class).withIdentity(jobKey).withDescription("first quartz job")
.usingJobData("JobDetailData", "Hello JobDetail").build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")
.withDescription("first quartz trigger").usingJobData("TriggerData", "Hello Trigger").startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).withRepeatCount(3))
.build();
return new JobModel(jobDetail, trigger);
}
/**
* CronJob初始化
*
* @param cronExpression Cron表达式
* @return
*/
private static JobModel InitCronJob(String cronExpression) {
JobKey jobKey = JobKey.jobKey("job2", "group1");
JobDetail jobDetail = JobBuilder.newJob(Job2.class).withIdentity(jobKey).withDescription("second quartz job")
.usingJobData("JobDetailData", "Hello JobDetail").build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger2", "group1")
.withDescription("second quartz trigger").usingJobData("TriggerData", "Hello Trigger").startNow()
// .endAt(DateTimeHelper.AddSecond(50))
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();
return new JobModel(jobDetail, trigger);
}
}
- 其他需要用到的类
package quartzDemo.quartz;
import org.quartz.JobDetail;
import org.quartz.Trigger;
public class JobModel {
private JobDetail jobDetail;
private Trigger trigger;
public JobDetail getJobDetail() {
return jobDetail;
}
public void setJobDetail(JobDetail jobDetail) {
this.jobDetail = jobDetail;
}
public Trigger getTrigger() {
return trigger;
}
public void setTrigger(Trigger trigger) {
this.trigger = trigger;
}
public JobModel() {
}
public JobModel(JobDetail jobDetail, Trigger trigger) {
super();
this.jobDetail = jobDetail;
this.trigger = trigger;
}
}
package quartzDemo.quartz;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeHelper {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
public static String Now() {
Date date = new Date();
return simpleDateFormat.format(date);
}
public static Date AddSecond(int second) {
Date date = new Date();
date.setTime(date.getTime() + second * 1000);
return date;
}
public static String Format(Date date, String pattern) {
if (!pattern.isEmpty()) {
pattern = "yyyy-MM-dd HH:MM:ss";
}
simpleDateFormat = new SimpleDateFormat(pattern);
return simpleDateFormat.format(date);
}
}
- 最后,运行App.java中的mian方法,查看输出,如下