官方的学习文档 http://www.quartz-scheduler.org/generated/2.2.1/html/qs-all/
package com.xh.market.business.time.service;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import java.util.List;
import org.quartz.CronExpression;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerMetaData;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xh.market.business.time.common.QuartzConstant;
import com.xh.market.business.time.entity.TimeTask;
import com.xh.market.business.time.job.TestJob;
import com.xh.market.business.time.util.QuartzScheduleUtil;
@Service
public class QuartzScheduleManager {
private Logger logger = LoggerFactory.getLogger(getClass());
private Scheduler scheduler = QuartzScheduleUtil.getInstanceScheduler();
@Autowired
private TimeTaskService timeTaskService;
public void run() throws SchedulerException {
try {
// Date runTime = evenMinuteDate(new Date());
JobDetail job = newJob(TestJob.class).withIdentity("job_0")
.requestRecovery().build();
Trigger trigger = newTrigger().withIdentity("trigger_0")
.withSchedule(cronSchedule("0/10 * * * * ?")).build();
// Trigger trigger = newTrigger().withIdentity("trigger_0")
// .withSchedule(cronSchedule("0 36 18 * * ?")).build();
if (!scheduler.checkExists(job.getKey())) {
scheduler.scheduleJob(job, trigger);
}
startScheduler();
} catch (Exception e) {
logger.error("run task error", e);
}
}
public void run(List taskList) {
try {
for (TimeTask task : taskList) {
try {
addJob(task);
} catch (Exception e) {
logger.error("add job error", e);
}
}
startScheduler();
} catch (Exception e) {
logger.error("run task error", e);
}
}
private void addJob(TimeTask task) throws SchedulerException {
Class clazz = null;
try {
clazz = Class.forName(task.getClassName());
} catch (Exception e) {
logger.error("class not found", e);
}
if (null != clazz) {
JobDetail jobDetail = newJob(clazz)
.withIdentity(QuartzConstant.PRE_JOB_NAME + task.getId())
.requestRecovery().build();
Trigger trigger = newTrigger()
.withIdentity(
QuartzConstant.PRE_TRIGGER_NAME + task.getId())
.withSchedule(cronSchedule(task.getCronExpress())).build();
if (!scheduler.checkExists(jobDetail.getKey())) {
scheduler.scheduleJob(jobDetail, trigger);
}
}
}
public void changeJob(TimeTask task, Integer actionType) throws Exception {
Class clazz = null;
try {
clazz = Class.forName(task.getClassName());
} catch (Exception e) {
logger.error("class not found", e);
throw new Exception("类不存在");
}
if (!CronExpression.isValidExpression(task.getCronExpress())) {
throw new Exception("表达式有误");
}
if (null != clazz) {
JobDetail jobDetail = newJob(clazz)
.withIdentity(QuartzConstant.PRE_JOB_NAME + task.getId())
.requestRecovery().build();
Trigger trigger = newTrigger()
.withIdentity(
QuartzConstant.PRE_TRIGGER_NAME + task.getId())
.withSchedule(cronSchedule(task.getCronExpress())).build();
if (null != actionType) {
switch (actionType) {
case QuartzConstant.ACTION_START:
if (!scheduler.checkExists(jobDetail.getKey())) {
scheduler.scheduleJob(jobDetail, trigger);
}
break;
case QuartzConstant.ACTION_STOP:
if (scheduler.checkExists(jobDetail.getKey())) {
scheduler.unscheduleJob(trigger.getKey());
}
break;
case QuartzConstant.ACTION_PAUSE:
if (scheduler.checkExists(jobDetail.getKey())) {
scheduler.pauseJob(jobDetail.getKey());
}
break;
case QuartzConstant.ACTION_RESUME:
if (scheduler.checkExists(jobDetail.getKey())) {
scheduler.resumeJob(jobDetail.getKey());
}
break;
case QuartzConstant.ACTION_RESTART:
if (scheduler.checkExists(jobDetail.getKey())) {
scheduler.unscheduleJob(trigger.getKey());
}
scheduler.scheduleJob(jobDetail, trigger);
break;
case QuartzConstant.ACTION_KEEP:
TriggerKey triggerKey = new TriggerKey(QuartzConstant.PRE_TRIGGER_NAME + task.getId());
Trigger triggerOld = scheduler.getTrigger(triggerKey);
if(null != triggerOld){
String state = scheduler.getTriggerState(triggerKey).name();
scheduler.unscheduleJob(triggerKey);
scheduler.scheduleJob(jobDetail, trigger);
if("PAUSED".equals(state)){
scheduler.pauseJob(jobDetail.getKey());
}
}
break;
default:
break;
}
}
startScheduler();
}
}
/** 启动Job */
public void startJob(Integer id) throws SchedulerException {
TimeTask task = timeTaskService.get(id);
addJob(task);
startScheduler();
}
/** 启动Job */
public void startJob(TimeTask task) throws SchedulerException {
addJob(task);
startScheduler();
}
/** 启动调度 */
private void startScheduler() throws SchedulerException {
if (!scheduler.isStarted()) {
scheduler.start();
}
SchedulerMetaData metaData = scheduler.getMetaData();
logger.info("executed " + metaData.getNumberOfJobsExecuted() + " jobs");
}
}
package com.xh.market.business.time.util;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.quartz.CronExpression;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import com.xh.market.business.time.common.QuartzConstant;
import com.xh.market.business.time.entity.TimeTask;
public class QuartzScheduleUtil {
private static Scheduler scheduler = getScheduler();
/** 创建一个调度对象 */
private static Scheduler getScheduler() {
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = null;
try {
scheduler = factory.getScheduler();
} catch (Exception e) {
e.printStackTrace();
}
return scheduler;
}
public static Scheduler getInstanceScheduler() {
return scheduler;
}
/** 获得job的执行情况 */
public static TimeTask getTaskInfo(TimeTask timeTask) throws SchedulerException {
JobKey jobKey = new JobKey(QuartzConstant.PRE_JOB_NAME + timeTask.getId());
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
TriggerKey triggerKey = new TriggerKey(QuartzConstant.PRE_TRIGGER_NAME + timeTask.getId());
Trigger trigger = scheduler.getTrigger(triggerKey);
if (null != jobDetail && null != trigger) {
JobDataMap data = jobDetail.getJobDataMap();
TriggerState state = scheduler.getTriggerState(triggerKey);//任务状态
timeTask.setState(state.name());
//Date startDate = trigger.getStartTime();
//Date endDate = trigger.getEndTime();
//Date finalDate = trigger.getFinalFireTime();
Date nextDate = trigger.getNextFireTime();// 下次执行时间
Date preDate = trigger.getPreviousFireTime();// 上次执行时间
if(null != preDate){
timeTask.setLastExecTime(preDate);
if(data.containsKey(QuartzConstant.KEY_USED_TIME)){
timeTask.setUsedTime(data.getLong(QuartzConstant.KEY_USED_TIME));
}
}
timeTask.setNextExecTime(nextDate);
if (data.containsKey(QuartzConstant.KEY_EXECUTION_COUNT)) {
timeTask.setExecCount(data.getInt(QuartzConstant.KEY_EXECUTION_COUNT));//执行次数
}
if(data.containsKey(QuartzConstant.KEY_EXCEPTION_COUNT)){
timeTask.setExceptionCount(data.getInt(QuartzConstant.KEY_EXCEPTION_COUNT));//异常数
}
if(data.containsKey(QuartzConstant.KEY_EXCEPTION_TIME)){
timeTask.setLastExceptionTime((Date)data.get(QuartzConstant.KEY_EXCEPTION_TIME));// 上次异常时间
}
if(data.containsKey(QuartzConstant.KEY_EXCEPTION_DESC)){
timeTask.setLastExceptionDesc(data.getString(QuartzConstant.KEY_EXCEPTION_DESC));// 上次异常描述
}
}
return timeTask;
}
/** 判断表达式是否正确 */
public static boolean validateCronExpression(String cronExpress){
return CronExpression.isValidExpression(cronExpress);
}
/** 判断类名是否正确 */
public static String validateClassName(String className){
Class clazz = null;
try {
clazz = Class.forName(className);
} catch (Exception e) {
return "该类不存在";
}
try {
JobBuilder.newJob(clazz).build();
} catch (Exception e) {
return "该类没有继承Job接口";
}
return null;
}
/** 启动一个调度对象 */
public void start() throws SchedulerException {
scheduler.start();
}
/** 检查调度是否启动 */
public boolean isStarted() throws SchedulerException {
return scheduler.isStarted();
}
/** 关闭调度信息 */
public void shutdown() throws SchedulerException {
scheduler.shutdown();
}
/** 添加调度的job信息 */
public Date scheduleJob(JobDetail jobDetail, Trigger trigger)
throws SchedulerException {
return scheduler.scheduleJob(jobDetail, trigger);
}
/** 添加相关的触发器 */
public Date scheduleJob(Trigger trigger) throws SchedulerException {
return scheduler.scheduleJob(trigger);
}
/** 添加多个job任务 */
/*public void scheduleJobs(Map> triggersAndJobs,
boolean replace) throws SchedulerException {
scheduler.scheduleJobs(triggersAndJobs, replace);
}*/
public void scheduleJobs(Map> triggersAndJobs,
boolean replace) throws SchedulerException {
scheduler.scheduleJobs(triggersAndJobs, replace);
}
/** 停止调度Job任务 */
public boolean unscheduleJob(TriggerKey triggerKey)
throws SchedulerException {
return scheduler.unscheduleJob(triggerKey);
}
/** 停止调度多个触发器相关的job */
public boolean unscheduleJobs(List triggerKeyList)
throws SchedulerException {
return scheduler.unscheduleJobs(triggerKeyList);
}
/** 重新恢复触发器相关的job任务 */
public Date rescheduleJob(TriggerKey triggerKey, Trigger trigger)
throws SchedulerException {
return scheduler.rescheduleJob(triggerKey, trigger);
}
/** 添加相关的job任务 */
public void addJob(JobDetail jobDetail, boolean flag)
throws SchedulerException {
scheduler.addJob(jobDetail, flag);
}
/** 删除相关的job任务 */
public boolean deleteJob(JobKey jobKey) throws SchedulerException {
return scheduler.deleteJob(jobKey);
}
/** 删除相关的多个job任务 */
public boolean deleteJobs(List jobKeys) throws SchedulerException {
return scheduler.deleteJobs(jobKeys);
}
public void triggerJob(JobKey jobKey) throws SchedulerException {
scheduler.triggerJob(jobKey);
}
public void triggerJob(JobKey jobKey, JobDataMap jobDataMap)
throws SchedulerException {
scheduler.triggerJob(jobKey, jobDataMap);
}
/** 停止一个job任务 */
public void pauseJob(JobKey jobKey) throws SchedulerException {
scheduler.pauseJob(jobKey);
}
/** 停止多个job任务 */
public void pauseJobs(GroupMatcher groupMatcher)
throws SchedulerException {
scheduler.pauseJobs(groupMatcher);
}
/** 停止使用相关的触发器 */
public void pauseTrigger(TriggerKey triggerKey) throws SchedulerException {
scheduler.pauseTrigger(triggerKey);
}
/** 停止多个触发器 */
public void pauseTriggers(GroupMatcher groupMatcher)
throws SchedulerException {
scheduler.pauseTriggers(groupMatcher);
}
/** 恢复相关的job任务 */
public void resumeJob(JobKey jobKey) throws SchedulerException {
scheduler.resumeJob(jobKey);
}
/** 恢复多个job任务 */
public void resumeJobs(GroupMatcher groupMatcher)
throws SchedulerException {
scheduler.resumeJobs(groupMatcher);
}
/** 恢复相关的Trigger */
public void resumeTrigger(TriggerKey triggerKey) throws SchedulerException {
scheduler.resumeTrigger(triggerKey);
}
/** 恢复多个Trigger */
public void resumeTriggers(GroupMatcher groupMatcher)
throws SchedulerException {
scheduler.resumeTriggers(groupMatcher);
}
/** 暂停调度中所有的job任务 */
public void pauseAll() throws SchedulerException {
scheduler.pauseAll();
}
/** 恢复调度中所有的job的任务 */
public void resumeAll() throws SchedulerException {
scheduler.resumeAll();
}
}