Quartz 是个开源的作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。Quartz框架包含了调度器监听、作业和触发器监听。你可以配置作业和触发器监听为全局监听或者是特定于作业和触发器的监听。Quartz 允许开发人员根据时间间隔(或天)来调度作业。它实现了作业和触发器的多对多关系,还能把多个作业与不同的触发器关联。整合了 Quartz 的应用程序可以重用来自不同事件的作业,还可以为一个事件组合多个作业。并且还能和spring配置整合使用。Quartz在功能上远远超越了JDK自带的Timer,很好很强大!好啦,直接上代码:
package
com.zoki.module.timer;
import
ch.qos.logback.classic.Logger;
import
java.util.Date;
import
java.util.Map;
import
java.util.Map.Entry;
import
java.util.concurrent.ConcurrentHashMap;
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.SimpleScheduleBuilder;
import
org.quartz.Trigger;
import
org.quartz.TriggerBuilder;
import
org.quartz.TriggerKey;
import
org.quartz.impl.StdSchedulerFactory;
import
org.slf4j.LoggerFactory;
/**
* 定时器任务调度管理器
*
* @author zhoukai
*/
public
class
QuartzManager {
private
final
String jobGroupName;
private
final
String triggerGroupName;
private
Scheduler sched;
private
final
static
SchedulerFactory sf =
new
StdSchedulerFactory();
private
final
static
Map<String, QuartzManager> instanceMap =
new
ConcurrentHashMap<>();
private
final
static
Logger logger = (Logger) LoggerFactory.getLogger(QuartzManager.
class
);
/**
* 构造方法,外部不能实例化
*
* @param jobGroupName 工作组名
* @param triggerGroupName 触发器组名
*/
private
QuartzManager(String jobGroupName, String triggerGroupName) {
this
.jobGroupName = jobGroupName;
this
.triggerGroupName = triggerGroupName;
}
/**
* 获取调度器
*
* @return 定时调度器
* @throws SchedulerException 调度器内部执行异常
*/
private
Scheduler getScheduler()
throws
SchedulerException {
if
(sched ==
null
) {
sched = sf.getScheduler();
//sched.getListenerManager().addTriggerListener(new QuartzTriggerListener());
//sched.getListenerManager().addSchedulerListener(new QuartzSchedulerListener(sched));
}
return
sched;
}
/**
* 获取一个定时调度管理器
*
* @param jobGroupName 工作组名
* @param triggerGroupName 触发器组名
* @return 定时调度管理器
*/
public
static
QuartzManager getInstance(String jobGroupName, String triggerGroupName) {
String instanceKey = jobGroupName +
"_"
+ triggerGroupName;
if
(instanceMap.containsKey(instanceKey)) {
return
instanceMap.get(instanceKey);
}
QuartzManager manager =
new
QuartzManager(jobGroupName, triggerGroupName);
instanceMap.put(instanceKey, manager);
return
manager;
}
/**
* 获取一个定时调度管理器
*
* @param groupName 工作组名和触发器组名相同
* @return 定时调度管理器
*/
public
static
QuartzManager getInstance(String groupName) {
return
getInstance(groupName, groupName);
}
/**
* 关闭调度器
*
* @param waitForJobsToComplete 是否等候所有工作被调度完成后再关闭
*/
public
void
shutdown(
boolean
waitForJobsToComplete) {
String instanceKey = jobGroupName +
"_"
+ triggerGroupName;
if
(instanceMap.containsKey(instanceKey)) {
QuartzManager manager = instanceMap.get(instanceKey);
if
(manager !=
null
&& manager.sched !=
null
) {
try
{
manager.sched.shutdown(waitForJobsToComplete);
}
catch
(SchedulerException ex) {
logger.debug(ex.getLocalizedMessage(), ex);
}
}
}
}
/**
* 关闭调度器
*/
public
void
shutdown() {
shutdown(
false
);
}
/**
* 添加一个调度任务
*
* @param jobName 任务名
* @param cls 任务类型
* @param start 任务执行的开始时间,null表示立刻执行
* @param end 任务执行的结束时间,null表示任务在执行repeat次数后自动结束
* @param jobBindData 绑定到job中的数据,可为null
* @param intervalType 任务执行时间间隔类型,1、毫秒,2、秒,3、分,4、小时,默认为2
* @param intervalValue 任务执行时间间隔
* @param repeat 任务执行次数,0表示执行一次,实际执行次数为此值+1
* @throws SchedulerException
*/
public
void
addJob(String jobName, Class cls, Date start, Date end, Map<String, Object> jobBindData,
int
intervalType,
long
intervalValue,
int
repeat)
throws
SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(jobName, jobGroupName).build();
if
(jobBindData !=
null
) {
for
(Entry<String, Object> entry : jobBindData.entrySet()) {
jobDetail.getJobDataMap().put(entry.getKey(), entry.getValue());
}
}
SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
switch
(intervalType) {
case
1
:
//毫秒
simpleScheduleBuilder.withIntervalInMilliseconds(intervalValue);
break
;
case
3
:
//分
simpleScheduleBuilder.withIntervalInMinutes((
int
) intervalValue);
break
;
case
4
:
//时
simpleScheduleBuilder.withIntervalInHours((
int
) intervalValue);
break
;
default
:
//秒
simpleScheduleBuilder.withIntervalInSeconds((
int
) intervalValue);
break
;
}
if
(repeat >=
0
) {
simpleScheduleBuilder.withRepeatCount(repeat);
}
TriggerBuilder<Trigger> builder = TriggerBuilder.newTrigger()
.withIdentity(jobName, triggerGroupName);
if
(start ==
null
) {
builder.startNow();
}
else
{
builder.startAt(start);
}
if
(end !=
null
) {
builder.endAt(end);
}
Trigger trigger = builder.withSchedule(simpleScheduleBuilder).build();
Scheduler scheduler = getScheduler();
scheduler.scheduleJob(jobDetail, trigger);
if
(!scheduler.isShutdown()) {
scheduler.start();
}
}
/**
* 添加一个调度任务,在start时间执行一次
* @param jobName 任务名
* @param cls 任务类型
* @param start 任务执行的开始时间,null表示立刻执行
* @param end 任务执行的结束时间,null表示任务在执行repeat次数后自动结束
* @param jobBindData 绑定到job中的数据,可为null
* @throws SchedulerException
*/
public
void
addJob(String jobName, Class cls, Date start , Date end, Map<String, Object> jobBindData)
throws
SchedulerException {
this
.addJob(jobName, cls, start, end, jobBindData,
2
,
1
,
0
);
}
/**
* 添加一个调度任务,在start时间执行一次
* @param jobName 任务名
* @param cls 任务类型
* @param start 任务执行的开始时间,null表示立刻执行
* @param jobBindData 绑定到job中的数据,可为null
* @throws SchedulerException
*/
public
void
addJob(String jobName, Class cls, Date start, Map<String, Object> jobBindData)
throws
SchedulerException {
this
.addJob(jobName, cls, start,
null
, jobBindData);
}
/**
* 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
*
* @param jobName 任务名
* @param cls
* @param time 时间设置,参考quartz说明文档
* @throws SchedulerException 调度器内部执行异常
*/
public
void
addJob(String jobName, Class cls, String time)
throws
SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(jobName, jobGroupName).build();
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(jobName, triggerGroupName)
//触发器名,触发器组
.withSchedule(CronScheduleBuilder.cronSchedule(time))
.build();
Scheduler scheduler = getScheduler();
scheduler.scheduleJob(jobDetail, trigger);
if
(!scheduler.isShutdown()) {
scheduler.start();
}
}
/**
* 移除一个任务
*
* @param triggerKey 触发器键
* @param jobKey 工作任务键
* @throws SchedulerException 调度器内部执行异常
*/
public
void
removeJob(TriggerKey triggerKey, JobKey jobKey)
throws
SchedulerException {
Scheduler scheduler = getScheduler();
scheduler.pauseTrigger(triggerKey);
scheduler.unscheduleJob(triggerKey);
scheduler.deleteJob(jobKey);
}
/**
* 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
*
* @param jobName 工作任务名
* @throws SchedulerException 调度器内部执行异常
*/
public
void
removeJob(String jobName)
throws
SchedulerException {
TriggerKey triggerKey =
new
TriggerKey(jobName, triggerGroupName);
JobKey jobKey =
new
JobKey(jobName, jobGroupName);
removeJob(triggerKey, jobKey);
}
}
- /**
- * @Description:
- *
- * @Title: QuartzManager.java
- * @Package com.joyce.quartz
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:15:52
- * @version V2.0
- */
- package com.joyce.quartz;
- import org.quartz.CronTrigger;
- import org.quartz.JobDetail;
- import org.quartz.Scheduler;
- import org.quartz.SchedulerFactory;
- import org.quartz.impl.StdSchedulerFactory;
- /**
- * @Description: 定时任务管理类
- *
- * @ClassName: QuartzManager
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:15:52
- * @version V2.0
- */
- public class QuartzManager {
- private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
- private static String JOB_GROUP_NAME = “EXTJWEB_JOBGROUP_NAME”;
- private static String TRIGGER_GROUP_NAME = “EXTJWEB_TRIGGERGROUP_NAME”;
- /**
- * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
- *
- * @param jobName
- * 任务名
- * @param cls
- * 任务
- * @param time
- * 时间设置,参考quartz说明文档
- *
- * @Title: QuartzManager.java
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:47:44
- * @version V2.0
- */
- @SuppressWarnings(“unchecked”)
- public static void addJob(String jobName, Class cls, String time) {
- try {
- Scheduler sched = gSchedulerFactory.getScheduler();
- JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, cls);// 任务名,任务组,任务执行类
- // 触发器
- CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);// 触发器名,触发器组
- trigger.setCronExpression(time);// 触发器时间设定
- sched.scheduleJob(jobDetail, trigger);
- // 启动
- if (!sched.isShutdown()) {
- sched.start();
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * @Description: 添加一个定时任务
- *
- * @param jobName
- * 任务名
- * @param jobGroupName
- * 任务组名
- * @param triggerName
- * 触发器名
- * @param triggerGroupName
- * 触发器组名
- * @param jobClass
- * 任务
- * @param time
- * 时间设置,参考quartz说明文档
- *
- * @Title: QuartzManager.java
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:48:15
- * @version V2.0
- */
- @SuppressWarnings(“unchecked”)
- public static void addJob(String jobName, String jobGroupName,
- String triggerName, String triggerGroupName, Class jobClass,
- String time) {
- try {
- Scheduler sched = gSchedulerFactory.getScheduler();
- JobDetail jobDetail = new JobDetail(jobName, jobGroupName, jobClass);// 任务名,任务组,任务执行类
- // 触发器
- CronTrigger trigger = new CronTrigger(triggerName, triggerGroupName);// 触发器名,触发器组
- trigger.setCronExpression(time);// 触发器时间设定
- sched.scheduleJob(jobDetail, trigger);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
- *
- * @param jobName
- * @param time
- *
- * @Title: QuartzManager.java
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:49:21
- * @version V2.0
- */
- @SuppressWarnings(“unchecked”)
- public static void modifyJobTime(String jobName, String time) {
- try {
- Scheduler sched = gSchedulerFactory.getScheduler();
- CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName,TRIGGER_GROUP_NAME);
- if (trigger == null) {
- return;
- }
- String oldTime = trigger.getCronExpression();
- if (!oldTime.equalsIgnoreCase(time)) {
- JobDetail jobDetail = sched.getJobDetail(jobName,JOB_GROUP_NAME);
- Class objJobClass = jobDetail.getJobClass();
- removeJob(jobName);
- addJob(jobName, objJobClass, time);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * @Description: 修改一个任务的触发时间
- *
- * @param triggerName
- * @param triggerGroupName
- * @param time
- *
- * @Title: QuartzManager.java
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:49:37
- * @version V2.0
- */
- public static void modifyJobTime(String triggerName,
- String triggerGroupName, String time) {
- try {
- Scheduler sched = gSchedulerFactory.getScheduler();
- CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerName,triggerGroupName);
- if (trigger == null) {
- return;
- }
- String oldTime = trigger.getCronExpression();
- if (!oldTime.equalsIgnoreCase(time)) {
- CronTrigger ct = (CronTrigger) trigger;
- // 修改时间
- ct.setCronExpression(time);
- // 重启触发器
- sched.resumeTrigger(triggerName, triggerGroupName);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
- *
- * @param jobName
- *
- * @Title: QuartzManager.java
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:49:51
- * @version V2.0
- */
- public static void removeJob(String jobName) {
- try {
- Scheduler sched = gSchedulerFactory.getScheduler();
- sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止触发器
- sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除触发器
- sched.deleteJob(jobName, JOB_GROUP_NAME);// 删除任务
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * @Description: 移除一个任务
- *
- * @param jobName
- * @param jobGroupName
- * @param triggerName
- * @param triggerGroupName
- *
- * @Title: QuartzManager.java
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:50:01
- * @version V2.0
- */
- public static void removeJob(String jobName, String jobGroupName,
- String triggerName, String triggerGroupName) {
- try {
- Scheduler sched = gSchedulerFactory.getScheduler();
- sched.pauseTrigger(triggerName, triggerGroupName);// 停止触发器
- sched.unscheduleJob(triggerName, triggerGroupName);// 移除触发器
- sched.deleteJob(jobName, jobGroupName);// 删除任务
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * @Description:启动所有定时任务
- *
- *
- * @Title: QuartzManager.java
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:50:18
- * @version V2.0
- */
- public static void startJobs() {
- try {
- Scheduler sched = gSchedulerFactory.getScheduler();
- sched.start();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * @Description:关闭所有定时任务
- *
- *
- * @Title: QuartzManager.java
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:50:26
- * @version V2.0
- */
- public static void shutdownJobs() {
- try {
- Scheduler sched = gSchedulerFactory.getScheduler();
- if (!sched.isShutdown()) {
- sched.shutdown();
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
以上就是quartz任务调度对于任务的常用操作,封装起来以便在外部调用!这样我们就需要任务的执行了:
- /**
- * @Description:
- *
- * @Title: QuartzJob.java
- * @Package com.joyce.quartz
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:37:11
- * @version V2.0
- */
- package com.joyce.quartz;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.quartz.Job;
- import org.quartz.JobExecutionContext;
- import org.quartz.JobExecutionException;
- /**
- * @Description: 任务执行类
- *
- * @ClassName: QuartzJob
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:37:11
- * @version V2.0
- */
- public class QuartzJob implements Job {
- @Override
- public void execute(JobExecutionContext arg0) throws JobExecutionException {
- System.out.println(new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”).format(new Date())+ “★★★★★★★★★★★”);
- }
- }
Ok,我们来测试一下:
- /**
- * @Description:
- *
- * @Title: QuartzTest.java
- * @Package com.joyce.quartz.main
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:35:05
- * @version V2.0
- */
- package com.joyce.quartz.main;
- import com.joyce.quartz.QuartzJob;
- import com.joyce.quartz.QuartzManager;
- /**
- * @Description: 测试类
- *
- * @ClassName: QuartzTest
- * @Copyright: Copyright (c) 2014
- *
- * @author Comsys-LZP
- * @date 2014-6-26 下午03:35:05
- * @version V2.0
- */
- public class QuartzTest {
- public static void main(String[] args) {
- try {
- String job_name = “动态任务调度”;
- System.out.println(“【系统启动】开始(每1秒输出一次)…”);
- QuartzManager.addJob(job_name, QuartzJob.class, “0/1 * * * * ?”);
- Thread.sleep(5000);
- System.out.println(“【修改时间】开始(每2秒输出一次)…”);
- QuartzManager.modifyJobTime(job_name, “10/2 * * * * ?”);
- Thread.sleep(6000);
- System.out.println(“【移除定时】开始…”);
- QuartzManager.removeJob(job_name);
- System.out.println(“【移除定时】成功”);
- System.out.println(“【再次添加定时任务】开始(每10秒输出一次)…”);
- QuartzManager.addJob(job_name, QuartzJob.class, “*/10 * * * * ?”);
- Thread.sleep(60000);
- System.out.println(“【移除定时】开始…”);
- QuartzManager.removeJob(job_name);
- System.out.println(“【移除定时】成功”);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
运行一下,看看效果图: