什么也不说直接上代码,代码的注释中有相关的讲解。
1、代码结构中用到的一些Jar包:
log4j-1.2.16.jar
quartz-2.2.1.jar
quartz-jobs-2.2.1.jar
slf4j-api-1.6.6.jar
slf4j-log4j12-1.6.6.jar
2、获取Scheduler对象:
package com.pitelin.quartz;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
/**
* 构建Scheduler工厂
* @author liZhongLin
*
*/
public class QuartzSchedulerFactory {
/**
* 定义静态Scheduler工厂
*/
private static SchedulerFactory schedulerFactory;
/**
* 执行静态代码块
*/
static {
schedulerFactory = new StdSchedulerFactory();
}
/**
* 返回一个Scheduler对象
* @return Scheduler
*/
public static Scheduler getInstance() {
try {
return QuartzSchedulerFactory.schedulerFactory.getScheduler();
} catch (SchedulerException e) {
e.printStackTrace();
}
return null;
}
}
3、获取CronTrigger对象:
package com.pitelin.quartz;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.CronTrigger;
import com.pitelin.quartz.entity.QuartzParamsEntity;
/**
* 根据给定的参数,获取CronTrigger
* @author liZhongLin
*
*/
public class QuartzCronTrigger {
/**
* 根据给定的参数,获取CronTrigger
* @param paramsEntity
* @return CronTrigger
*/
public static CronTrigger getCronTrigger(QuartzParamsEntity paramsEntity) {
String trigger = paramsEntity.getTriggerName();
String group = paramsEntity.getGroupName();
String cronExpression = paramsEntity.getCronExpression();
return newTrigger().withIdentity(trigger, group).withSchedule(cronSchedule(cronExpression)).build();
}
}
4、获取JobDetail对象:
package com.pitelin.quartz;
import static org.quartz.JobBuilder.newJob;
import org.quartz.JobDetail;
import com.pitelin.quartz.entity.QuartzParamsEntity;
/**
* 根据给定的参数获取JobDetail对象
* @author liZhongLin
*
*/
public class QuartzJobDetail {
/**
* 根据给定的参数获取JobDetail对象
* @param paramsEntity
* @return JobDetail
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static JobDetail getJobDetail(QuartzParamsEntity paramsEntity) {
Class jobClass = paramsEntity.getJobClass();
String jobName = paramsEntity.getJobName();
String groupName = paramsEntity.getGroupName();
return newJob(jobClass).withIdentity(jobName, groupName).build();
}
}
5、启动和关闭Job线程:
package com.pitelin.quartz;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import com.pitelin.quartz.entity.QuartzParamsEntity;
/**
*
* 1、Job表示一个工作,要执行的具体内容。此接口中只有一个方法:void execute(JobExecutionContext context)
* 2、JobDetail表示一个具体的可执行的调度程序,Job是这个可执行程调度程序所要执行的内容,另外JobDetail还包含了这个任务调度的方案和策略。
* 3、Trigger代表一个调度参数的配置,什么时候去调用。
* 4、Scheduler代表一个调度容器,一个调度容器中可以注册多个JobDetail和Trigger。当Trigger与JobDetail组合,就可以被Scheduler容器调度了。
*
* @author liZhongLin
*
*/
public class QuartzJobStart {
/**
* 定义静态Scheduler
*/
private static Scheduler sched;
/**
* 执行静态代码块
*/
static{
sched = QuartzSchedulerFactory.getInstance();
}
/**
* Job线程启动操作
* @param paramsEntity
* @throws SchedulerException
*/
public static void start(QuartzParamsEntity paramsEntity) throws SchedulerException {
JobDetail job = QuartzJobDetail.getJobDetail(paramsEntity);
CronTrigger trigger = QuartzCronTrigger.getCronTrigger(paramsEntity);
sched.scheduleJob(job, trigger);
sched.start();
}
/**
* Job线程关闭操作
* @throws SchedulerException
*/
public static void stop() throws SchedulerException {
sched.shutdown(true);
}
}
6、定义一个Job参数实体:
package com.pitelin.quartz.entity;
/**
* 定时任务参数实体
* @author liZhongLin
*
*/
public class QuartzParamsEntity {
/**
* 执行定时任务的class extends Job>
*/
private Class> jobClass;
/**
* trigger名称
*/
private String triggerName;
/**
* job名称
*/
private String jobName;
/**
* group名称
*/
private String groupName;
/**
* 定时任务表达式
*/
private String cronExpression;
}
7、编写两个简单的Job:
第一个JOB:
package com.pitelin.quartz.job;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* 生成一个当前时间的JOB
* @author liZhongLin
*
*/
public class DateJob implements Job{
/**
* 日志信息
*/
private final Logger log = LoggerFactory.getLogger(DateJob.class);
/**
* 获取当前的时间
*/
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
log.debug("现在的时间为:" + sdf.format(new Date()));
}
}
package com.pitelin.quartz.job;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 生成一个1-100的随机数的JOB
* @author liZhongLin
*
*/
public class RandomJob implements Job {
/**
* 日志信息
*/
private final Logger log = LoggerFactory.getLogger(RandomJob.class);
/**
* 生成一个1-100的随机数
*/
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
int random = (int)(Math.random()*100);
log.debug("生成的随机数为:" + random);
}
}
8、测试Job:
package com.pitelin.quartz.test;
import com.pitelin.quartz.QuartzJobStart;
import com.pitelin.quartz.entity.QuartzParamsEntity;
import com.pitelin.quartz.job.DateJob;
import com.pitelin.quartz.job.RandomJob;
/**
* 任务调度测试类
* @author liZhongLin
*
*/
public class QuartzJobTest {
/**
* 主方法
* 这里的输入参数使用了硬编码的方式,最合理的方式是可以把这些参数存放到数据库当中。
* 之后根据查询的结果赋给List,并循环执行任务调度
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
QuartzParamsEntity paramsEntityOne = new QuartzParamsEntity();
paramsEntityOne.setJobClass(DateJob.class);
paramsEntityOne.setJobName("myJobOne");
paramsEntityOne.setGroupName("myGroup");
paramsEntityOne.setTriggerName("myTriggerOne");
paramsEntityOne.setCronExpression("0/1 * * * * ?");//每个一秒执行一次
QuartzParamsEntity paramsEntityTwo = new QuartzParamsEntity();
paramsEntityTwo.setJobClass(RandomJob.class);
paramsEntityTwo.setJobName("myJobTwo");
paramsEntityTwo.setGroupName("myGroup");
paramsEntityTwo.setTriggerName("myTriggerTwo");
paramsEntityTwo.setCronExpression("0/2 * * * * ?");//每个两秒执行一次
QuartzJobStart.start(paramsEntityOne);
QuartzJobStart.start(paramsEntityTwo);
Thread.sleep(6000);//线程休眠六秒时间
QuartzJobStart.stop();
}
}
9:、附上log4j.properties资源文件配置:
log4j.rootLogger =ALL,systemOut
#输出到控制台
log4j.appender.systemOut = org.apache.log4j.ConsoleAppender
log4j.appender.systemOut.layout = org.apache.log4j.PatternLayout
log4j.appender.systemOut.layout.ConversionPattern = %-22d{yyyy-MM-dd HH:mm:ss}[%-5p][%l]%m%n
log4j.appender.systemOut.Threshold = DEBUG
log4j.appender.systemOut.ImmediateFlush = TRUE
log4j.appender.systemOut.Target = System.out