1. 引入jar包:quartz-jobs-2.2.3.jar,quartz-2.2.3.jar
2. 添加配置文件quartz.xml
3. 创建QuartzManager定时任务管理工具类
4. 创建定时任务实现类,将业务写在execute( )方法中
5. 根据业务需求管理定时任务
quartz.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- 这个类用来做需要完成的业务-->
<bean id="blankJob" class="***.***.***.BlankJob"/>
<bean id="springContextUtil" class="***.***.***.SpringContextUtil"></bean>
<!-- 定时任务 -->
<!-- 定义调用对象和调用对象的方法,这个配置和普通的一样的,id是JobDetail的名字 -->
<bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 调用的类 -->
<property name="targetObject" ref="blankJob" />
<!-- 调用类中的方法 -->
<property name="targetMethod" value="doNothing" />
<!-- 是否并发 -->
<property name ="concurrent" value ="false" />
</bean>
<!-- 定义触发时间和定时任务实现类-->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean ">
<property name="jobDetail" ref="jobtask" />
<!-- cron表达式 -->
<property name="cronExpression" value="0 0 0 * * ?" />
</bean>
<!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuertz" lazy-init="true" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<!-- 手动配置定时任务,根据需要配置 -->
<!-- <ref bean="cronTrigger" /> -->
</list>
</property>
</bean>
<!--这个类是用来设置触发时间的, startJobs方法启动调度容器 -->
<bean id="quartzManager" class="***.***.***.QuartzManager" lazy-init="false" init-method="startJobs" >
<!--这个对象一定要注入,这样类才能进行管理,还有在类型要用get set方法,不然会报错。-->
<property name="scheduler" ref="startQuertz" />
</bean>
</beans>
QuartzManager.java
import java.util.List;
import javax.annotation.Resource;
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.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
public class QuartzManager {
@Resource
private ScenarioMapper scenarioMapper;
private Scheduler scheduler;
public Scheduler getScheduler() {
return scheduler;
}
public void setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
}
/**
* 功能: 添加一个定时任务
* @param jobName 任务名
* @param jobGroupName 任务组名
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @param jobClass 任务的类类型 eg:TimedMassJob.class
* @param cron 时间设置 表达式,参考quartz说明文档
*/
public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass, String cron,Object...objects) {
try {
// 任务名,任务组,任务执行类
JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
// 触发器
if(objects!=null){
for (int i = 0; i < objects.length; i++) {
//该数据可以通过Job中的JobDataMap dataMap = context.getJobDetail().getJobDataMap();来进行参数传递值
jobDetail.getJobDataMap().put("data"+(i+1), objects[i]);
}
}
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(triggerName,triggerGroupName);
triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
// 创建Trigger对象
CronTrigger trigger = (CronTrigger) triggerBuilder.build();
// 调度容器设置JobDetail和Trigger
scheduler.scheduleJob(jobDetail, trigger);
// 启动
/*if (!scheduler.isShutdown()) {
scheduler.start();
}*/
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 功能:修改一个任务的触发时间
* @param jobName
* @param jobGroupName
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @param cron 时间设置,参考quartz说明文档
*/
public void modifyJobTime(String jobName, String jobGroupName, String triggerName, String triggerGroupName, String cron) {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
if (trigger == null) {
return;
}
String oldTime = trigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(cron)) {
// 触发器
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(triggerName, triggerGroupName);
triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
// 创建Trigger对象
trigger = (CronTrigger) triggerBuilder.build();
// 方式一 :修改一个任务的触发时间
scheduler.rescheduleJob(triggerKey, trigger);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 功能: 移除一个任务
* @param jobName
* @param jobGroupName
* @param triggerName
* @param triggerGroupName
*/
public void removeJob(String jobName, String jobGroupName,String triggerName, String triggerGroupName) {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);
// 停止触发器
scheduler.pauseTrigger(triggerKey);
// 移除触发器
scheduler.unscheduleJob(triggerKey);
// 删除任务
scheduler.deleteJob(JobKey.jobKey(jobName,jobGroupName));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*
* 功能:启动所有定时任务,可以在这里初始化数据库中的定时任务
*/
public void startJobs() {
try {
scheduler.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 功能:关闭所有定时任务
*/
public void shutdownJobs() {
try {
if (!scheduler.isShutdown()) {
scheduler.shutdown();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
cron格式转化工具类
import java.text.DecimalFormat;
public class QuartzCronDateUtils {
/***
*根据自己的需要编写转化方法即可 * * * * * ?:秒 分 时 日 月 星期(日和星期冲突,需把一个设为?)
* @param time HH:mm:ss
* @param weekdays 星期(bit0:周日;bit1:周一;...;bit6:周六)
* @return
*/
public static String getCron(String time,int weekdays){
String[] str = time.split(":");
String second = str[2];
String minute = str[1];
String hour = str[0];
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(second).append(" ").append(minute).append(" ").append(hour).append(" ? * ");
String week = Integer.toBinaryString(weekdays);
DecimalFormat df = new DecimalFormat("0000000");
week = df.format(Integer.parseInt(week));
for (int i = 6; i >= 0; i--) {
if (Integer.valueOf(week.substring(i, i+1)) == 1) {
stringBuffer.append((7-i) + ",");
}
}
String cron = stringBuffer.toString();
return cron.substring(0, cron.length()-1);
}
}
定时任务实现类TaskJob.java
import java.util.List;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.context.ApplicationContext;
//实现Job接口的execute方法
public class TaskJob implements Job {
private int taskId;
public TaskJob(int taskId) {
this.taskId = taskId;
}
public TaskJob() {
}
public int getTaskId() {
return taskId;
}
@Override
public void execute(JobExecutionContext arg0) {
//可根据argo参数,获取定时任务的相关属性
JobDataMap jobDataMap = arg0.getMergedJobDataMap();
TaskJob jobDemo = (TaskJob)jobDataMap.get("data1");
System.out.println(jobDemo.taskId);
}
}