如题所示,本篇的主要内容是介绍如何对quratz的任务动态添加、删除及修改
package com.hrt.quartz;
import java.text.ParseException;
import java.util.List;
import java.util.Date;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
/**
* 定时任务管理
* @author JP
*
*/
public interface QuartzManager {
/**
* 添加简单任务,只运行一次的任务
* @param jobname
* @param jobGroup
* @param jobClass
* @param runTime 格式 :yyyyMMddHHmmss
* @param arrayParam
*/
public void addSimpleJob(String jobname, String jobGroup, Class jobClass, Date runTime, List arrayParam);
/**
* 添加循环任务,特定时间循环运行,例如每个星期3,12点运行等
* @param jobname
* @param jobGroup
* @param jobClass
* @param crontime
* @param arrayParam
*/
public void addCronJob(String jobname,String jobGroup,Class jobClass,String crontime,List arrayParam);
/**
* 修改简单任务,一般指修改运行的时间
* @param jobName
* @param jobGroup
* @param runDateTime
*/
void updateSimpleJob(String jobName, String jobGroup, Date runDateTime);
/**
* 修改cron任务,一般指修改循环运行时间
* @param jobName
* @param jobGroup
* @param cronTime
*/
public void updateCronJob(String jobName, String jobGroup, String cronTime);
/**
* 移除所有任务
*/
public void deleteAll();
/**
* 移除任务
* @param jobName
* @param jobGroup
*/
public void deleteJob(String jobName, String jobGroup);
/**
* 暂停任务
* @param jobName
* @param jobGroup
*/
public void pauseJob(String jobName, String jobGroup);
/**
* 暂停所有任务
*/
public void pauseAll();
/**
* 恢复某个任务
*
* @param jobName
* @param jobGroup
*/
public void resumeJob(String jobName, String jobGroup) ;
/**
* 恢复所有
*/
public void resumeAll() ;
/**
* 关闭任务调度器
*/
public void shutDown();
/**
* 开启任务调度器
*/
public void startScheduler() ;
}
然后就是去实现这个接口里的方法,方便后面使用
package com.hrt.quartz;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
import java.util.Date;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
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.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.triggers.CronTriggerImpl;
public class QuartzManagerImpl implements QuartzManager{
private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
/**
* 添加简单任务,只运行一次的任务
* @param jobname
* @param jobGroup
* @param jobClass
* @param runTime 格式 :Date
* @param arrayParam
*/
@Override
public void addSimpleJob(String jobname, String jobGroup, Class jobClass, Date runTime, List arrayParam) {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
//判断是否已存在相同jobName,jobGroup,若存在则删除
if(sched.getJobDetail(JobKey.jobKey(jobname,jobGroup))!=null) {
deleteJob(jobname, jobGroup);
}
JobDetail jobDetail=JobBuilder.newJob(jobClass)
.withIdentity(jobname, jobGroup)
.build();
jobDetail.getJobDataMap().put("scheduleJob",arrayParam);
//创建SimpleTrigger,在特定时间仅运行一次
SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger().withIdentity(jobname, jobGroup).
startAt(runTime).build();
sched.scheduleJob(jobDetail, trigger);
// 启动
if(!sched.isShutdown()) {
sched.start();
}
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void addCronJob(String jobname, String jobGroup, Class jobClass, String crontime, List arrayParam) {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
//判断是否已存在相同jobName,jobGroup,若存在则删除
if(sched.getJobDetail(JobKey.jobKey(jobname,jobGroup))!=null) {
deleteJob(jobname, jobGroup);
}
JobDetail jobDetail=JobBuilder.newJob(jobClass)
.withIdentity(jobname, jobGroup)
.build();
jobDetail.getJobDataMap().put("scheduleJob",arrayParam);
//创建CronTrigger,在特定时间循环运行
CronTrigger trigger = (CronTrigger) TriggerBuilder.newTrigger().withIdentity(jobname, jobGroup)
.withSchedule(CronScheduleBuilder.cronSchedule(crontime))// 日历
.build();
sched.scheduleJob(jobDetail, trigger);
// 启动
if(!sched.isShutdown()) {
sched.start();
}
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 修改SimpleJob任务时间
*/
@Override
public void updateSimpleJob(String jobName, String jobGroup, Date runDateTime) {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
SimpleTrigger trigger = (SimpleTrigger) sched.getTrigger(triggerKey);
if (trigger == null) {
return;
}
// 触发器
TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(jobName, jobGroup);
// 触发器时间设定
triggerBuilder.startAt(runDateTime);
// 创建Trigger对象
trigger = (SimpleTrigger) triggerBuilder.build();
// 按新的触发器重新设置Job执行
sched.rescheduleJob(triggerKey, trigger);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 修改CronJob 任务周期
*/
@Override
public void updateCronJob(String jobName, String jobGroup, String cronTime) {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
CronTrigger trigger = (CronTrigger)sched.getTrigger(triggerKey);
if (trigger == null) {
return;
}
String oldTime = trigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(cronTime)) {
// 触发器
TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(jobName, jobGroup);
triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cronTime));
// 创建Trigger对象
trigger = (CronTrigger) triggerBuilder.build();
// 按新的触发器重新设置Job执行
sched.rescheduleJob(triggerKey, trigger);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 删除任务组名为group_1的所有任务
*/
@Override
public void deleteAll() {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
GroupMatcher matcher = GroupMatcher.groupEquals("group_1"); //得修改
Set jobkeySet = sched.getJobKeys(matcher);
List jobkeyList = new ArrayList();
jobkeyList.addAll(jobkeySet);
sched.deleteJobs(jobkeyList);
System.out.println("删除所有组别为group_1的任务");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 删除单个任务
*/
@Override
public void deleteJob(String jobName, String jobGroup) {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
sched.pauseTrigger(TriggerKey.triggerKey(jobName, jobGroup));// 停止触发器
sched.unscheduleJob(TriggerKey.triggerKey(jobName, jobGroup));// 移除触发器
sched.deleteJob(JobKey.jobKey(jobName, jobGroup));// 删除任务
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 关闭所有定时器
*/
@Override
public void shutDown() {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
if (!sched.isShutdown()) {
sched.shutdown();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 启动所有的定时器
*/
@Override
public void startScheduler() {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
sched.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 暂停单个任务
*/
@Override
public void pauseJob(String jobName, String jobGroup) {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
sched.pauseJob(JobKey.jobKey(jobName, jobGroup));
sched.pauseTrigger(TriggerKey.triggerKey(jobName, jobGroup));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 暂停所有任务
*/
@Override
public void pauseAll() {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
sched.pauseAll();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 恢复单个任务
*/
@Override
public void resumeJob(String jobName, String jobGroup) {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
sched.resumeJob(JobKey.jobKey(jobName, jobGroup));
sched.resumeTrigger(TriggerKey.triggerKey(jobName, jobGroup));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 恢复所有任务
*/
@Override
public void resumeAll() {
// TODO Auto-generated method stub
try {
Scheduler sched = gSchedulerFactory.getScheduler();
sched.resumeAll();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
再去弄一个具体的job类,去执行具体的工作
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class QuartzJob implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// TODO Auto-generated method stub
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ ".........");
}
}
接下来就是去调用方法,动态的管理任务。这里我就写了两种触发器添加任务的方法,其他方法可自己调用测试。
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.hrt.quartz.QuartzJob;
import com.hrt.quartz.QuartzManager;
import com.hrt.quartz.QuartzManagerImpl;
import com.hrt.util.DateCron;
public class TestQuartz {
public static void main(String[] args) {
executeSimpleJob();//以Simple触发器添加的定时任务
executeCronJob(); //以Cron触发器添加的定时任务
//QuartzManager q=new QuartzManagerImpl();
//q.deleteAll(); 删除所有
}
//测试SImpleJob方法
public static void executeSimpleJob() {
QuartzManagerImpl q=new QuartzManagerImpl();
String job_name="一个simpleJob任务";
String jobGroup="Group12";
//指定执行时间
String time="2019-01-23 16:07:31";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
//字符时间转时间类型
date = format.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Simple【系统启动】开始在2019-01-23 16:07:31执行");
//传参
List list=new ArrayList<>();
q.addSimpleJob(job_name, jobGroup, QuartzJob.class, date, list);
//q.deleteJob(job_name, jobGroup);
}
//测试CronJob方法
public static void executeCronJob() {
QuartzManagerImpl q=new QuartzManagerImpl();
String job_name="Cron触发器在指定时间循环执行";
String jobGroup="Group12";
/* //转换出Cron时间
String Crontime=DateCron.cronTime(date, "1");
System.out.println("Cron时间表达试:" +Crontime);*/
String str="0/5 * * * * ? ";
System.out.println("CronJOb【系统启动】(每5秒输出一次)...");
List list=new ArrayList<>();
q.addCronJob(job_name, jobGroup, QuartzJob.class, str, list);
//q.deleteJob(job_name, jobGroup);
}
}