很多时候,spring的quartz定时任务并不能完全满足项目的需要,经常会遇到需要任务的执行时间和频率是可控的,而不是写死在 quartz配置xml上面。为此,思考了很多动态修改任务执行的方法,以下方法是通过获取scheduler,对trigger的时间表达式进行修改,并重启任务去实现任务的动态变化。
public class QuartzHandler {
public static final String DEFAULT_GROUP_NAME = "DEFAULT";
private static QuartzHandler instance = new QuartzHandler();
private static Logger logger = Logger.getLogger(QuartzHandler.class);
private QuartzManager quartzManager;
private Scheduler scheduler;
private ApplicationContext context;
private QuartzHandler() {
}
public static QuartzHandler genInstance() {
return instance;
}
/**
* 开始定时任务
*/
public void start() {
context = new ClassPathXmlApplicationContext(
"spring/applicationContext.xml");
scheduler = (StdScheduler) context.getBean("schedulerFactory");
quartzManager = (QuartzManager) context.getBean("quartzManager");
}
/**
* 更新定时任务的触发表达式
*
* @param triggerName
* 触发器名字
* @param groupName
* 触发器组名字
* @param cronExpression
* 触发表达式
* @return 成功则返回true,否则返回false
*/
public boolean updateCronExpression(String triggerName, String groupName,
String cronExpression) {
try {
CronTrigger trigger = (CronTrigger) getTrigger(triggerName,
groupName);
if (trigger == null) {
return false;
}
if (StringUtils.equals(trigger.getCronExpression(), cronExpression)) {
logger.info("cronExpression is same with the running Schedule , no need to update.");
return true;
}
trigger.setCronExpression(cronExpression);
scheduler.rescheduleJob(trigger.getName(), trigger.getGroup(),
trigger);
logger.info("Update the cronExpression successfully!!");
return true;
} catch (ParseException e) {
logger.error("The new cronExpression - " + cronExpression
+ " not conform to the standard. " + e);
return false;
} catch (SchedulerException e) {
logger.error("Fail to reschedule. " + e);
return false;
}
}
/**
* 获取触发器
*
* @param triggerName
* 触发器名字
* @param groupName
* 触发器组名字
* @return 对应Trigger
*/
public Trigger getTrigger(String triggerName, String groupName) {
Trigger trigger = null;
if (StringUtils.isBlank(groupName)) {
logger.warn("Schedule Job Group is empty!");
return null;
}
if (StringUtils.isBlank(triggerName)) {
logger.warn("Schedule trigger Name is empty!");
return null;
}
try {
trigger = scheduler.getTrigger(triggerName, groupName);
} catch (SchedulerException e) {
logger.warn("Fail to get the trigger (triggerName: " + triggerName
+ ", groupName : " + groupName + ")");
return null;
}
if (trigger == null) {
logger.warn("Can not found the trigger of triggerName: "
+ triggerName + ", groupName : " + groupName);
}
return trigger;
}
}