quartz 数据库可配置
一、表设计:
DROP TABLE IF EXISTS `ma_quartz_info`;
CREATE TABLE `ma_quartz_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(32) DEFAULT '' COMMENT '定时任务名称',
`code` varchar(64) DEFAULT '' COMMENT '定时任务code标识',
`cycle` varchar(32) DEFAULT '' COMMENT '定时任务执行周期',
`class_name` varchar(64) DEFAULT '' COMMENT '定时任务执行类',
`succeed` int(11) DEFAULT '0' COMMENT '成功执行次数',
`fail` int(11) DEFAULT '0' COMMENT '失败执行次数',
`state` varchar(2) DEFAULT '' COMMENT '是否启用 10启用 20禁用',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`init_data_url` varchar(100) DEFAULT NULL COMMENT '初始化数据url',
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='定时任务信息表';
INSERT INTO ma_quartz_info(name, code, cycle, class_name, state, init_data_url) VALUES ('用户行为','applicantsBehavior','0 57 2 * * ?','com.jxl.manado.job.ApplicantsBehaviorJob','10','/manado/userAnalysis/deleteUserBehavior.api');
DROP TABLE IF EXISTS `ma_quartz_log`;
CREATE TABLE `ma_quartz_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`quartz_id` bigint(20) DEFAULT NULL COMMENT '定时任务id',
`start_time` datetime DEFAULT NULL COMMENT '启动时间',
`time` int(11) DEFAULT '0' COMMENT '任务用时',
`result` varchar(2) DEFAULT '' COMMENT '执行结果 10成功 20失败',
`remark` varchar(128) DEFAULT '' COMMENT '备注信息',
PRIMARY KEY (`id`),
KEY `quartz_id` (`quartz_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='定时任务执行记录表';
(quartzInfoService 和 quartzInfoDao 略)
二、QuartzManager
@Service
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";
public static final Logger logger = LoggerFactory
.getLogger(QuartzManager.class);
@Autowired
private Scheduler scheduler;
/**
* 添加一个定时任务
*
* @param jobName
* @param time
*/
public void addJob(String jobName,String jobClassName, String time) {
try {
Class jobClass = Class.forName(jobClassName);
// Scheduler scheduler = gSchedulerFactory.getScheduler();
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, JOB_GROUP_NAME).build();// 任务名,任务组,任务执行类
// 触发器
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time);
//按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, TRIGGER_GROUP_NAME).withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
// 启动
if (!scheduler.isShutdown()) {
scheduler.start();
}
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
} catch (ClassNotFoundException e) {
logger.error(e.getMessage(), e);
}
}
/**
* 修改一个任务的触发时间
*
* @param Jobname
* @param time
* @param time
*/
public void modifyJobTime(String Jobname,String time) {
try {
// Scheduler scheduler = gSchedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(Jobname, TRIGGER_GROUP_NAME);
//获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
if (trigger == null) {
return;
}
String oldTime = trigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(time)) { //表达式调度构建器
// 修改时间
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time);
//按新的cronExpression表达式构建一个新的trigger
trigger = TriggerBuilder.newTrigger().withIdentity(Jobname, TRIGGER_GROUP_NAME).withSchedule(scheduleBuilder).build();
// 重启触发器
scheduler.rescheduleJob(triggerKey, trigger);
}
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
}
/**
* 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
*
* @param jobName
*/
public void removeJob(String jobName) {
try {
// Scheduler scheduler = gSchedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME);
scheduler.pauseTrigger(triggerKey);// 停止触发器
scheduler.unscheduleJob(triggerKey);// 移除触发器
scheduler.deleteJob(JobKey.jobKey(jobName, JOB_GROUP_NAME));// 删除任务
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
}
/**
* 立即执行任务(使用默认的任务组名,触发器名,触发器组名)
*
* @param jobName
*/
public void startJobNow(String jobName) {
try {
// Scheduler scheduler = gSchedulerFactory.getScheduler();
scheduler.triggerJob(JobKey.jobKey(jobName, JOB_GROUP_NAME));
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
}
/**
* 启动所有定时任务
*/
public void startJobs() {
try {
// Scheduler scheduler = gSchedulerFactory.getScheduler();
scheduler.start();
} catch (SchedulerException e) {
logger.error(e.getMessage(),e);
}
}
/**
* 关闭所有定时任务
*/
public void shutdownJobs() {
try {
// Scheduler scheduler = gSchedulerFactory.getScheduler();
if (!scheduler.isShutdown()) {
scheduler.shutdown();
}
} catch (SchedulerException e) {
logger.error(e.getMessage(),e);
}
}
}
三、QuartzJobListener
public class QuartzJobListener extends QuartzInitializerListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
super.contextInitialized(servletContextEvent);
QuartzManager quartzManager = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext()).getBean(QuartzManager.class);
QuartzInfoService quartzInfoService = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext()).getBean(QuartzInfoService.class);
List<QuartzInfo> quartzInfoList = quartzInfoService.findAllUsedQuartzJobs();
if(Detect.notEmpty(quartzInfoList)){
for(QuartzInfo quartzInfo : quartzInfoList){
quartzManager.addJob(quartzInfo.getCode(), quartzInfo.getClassName(), quartzInfo.getCycle());
}
}
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
super.contextDestroyed(servletContextEvent);
}
}
上一篇: 大哥,你赢了!
下一篇: [Redis] 哈希类型与ziplist