springboot+quartz定时任务
SpringBoot和Quartz实现定时任务
Springboot的程序需要在启动的时候初始化并启动几个定时任务
配置类
StartupListener Bean定义
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SyncDataConfig {
@Bean
// 控制配置类是否生效
@ConditionalOnProperty(
prefix = "sync-data", // 属性前缀
name = {"enable"}, // 属性名
havingValue = "true" // 期望值
)
// @ConditionalOnClass(Po.class) // 只有在有这个类存在的时候才生效 否则无法创建定时任务
public SyncDataTaskStartupListener syncDataTaskStartupListener(TaskService taskService){
return new SyncDataTaskStartupListener(taskService);
}
}
StartupListener
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextStoppedEvent;
public class SyncDataTaskStartupListener implements ApplicationListener<ApplicationEvent> {
protected final Logger log = LoggerFactory.getLogger(SyncDataTaskStartupListener.class);
private TaskService taskService;
public SyncDataTaskStartupListener(TaskService taskService) {
this.taskService = taskService;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (!(event instanceof ContextClosedEvent) && !(event instanceof ContextStoppedEvent)) {
if (event instanceof ApplicationReadyEvent) {
this.log.info("------>初始化SyncDataTask start");
this.taskService.initTask(); // 初始化定时任务
this.log.info("------>初始化SyncDataTask end");
}
}
}
}
Task定义
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SyncDataTask implements Job {
private static final Logger logger = LoggerFactory.getLogger(SyncDataTask.class);
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
SyncDataManage syncDataManage = SpringBeanUtil.getBean(SyncDataManage.class);
try {
// 获取定时任务的一些自定义参数
String sjbId = (String) context.getMergedJobDataMap().get("sjbId");
Integer sjbType = (Integer) context.getMergedJobDataMap().get("sjbType");
logger.info("执行定时任务: taskname->{} : sjbId->{}, sjbType->{}", context.getJobDetail().getDescription(), sjbId,sjbType);
// 定时任务中要做的事情.......
logger.info("执行定时任务成功: taskname->{} : sjbId->{}, sjbType->{}", context.getJobDetail().getDescription(), sjbId,sjbType);
} catch (Exception e) {
logger.error("执行定时任务失败: mc->{}, desc->{}", context.getJobDetail().getKey().getName(),
context.getJobDetail().getDescription());
logger.error(e.getMessage(), e);
}
}
}
initTask Task初始化方法
@Override
public void initTask() {
log.info("初始化定时任务");
try {
// 创建trigger
CronTriggerImpl trigger = new CronTriggerImpl();
trigger.setName(po.getId());
trigger.setMisfireInstruction(2);
trigger.setCronExpression("cron表达式");
// 构建job
JobBuilder jobBuilder = JobBuilder.newJob(SyncDataTask.class) // 指定Job类
.withDescription(po.getSjbid())
.withIdentity(po.getId())
.usingJobData("sjbId", po.getSjbid()) // 自定义参数信息 给Task用
.usingJobData("sjbType", po.getSjbType());
JobDetail job = jobBuilder.build();
this.log.info("启动定时任务:{}>>>{}", po.getSjbid(), po.getId());
this.factory.getScheduler().scheduleJob(job, trigger);
} catch (Exception e) {
e.printStackTrace();
log.error("初始化定时任务失败:" + e.getMessage(), e);
}
}