springboot 中添加定时任务管理
springboot 定时任务在各项开发项目中,定时任务往往是不可缺少的一部分,前期时候任务量不多,直接配置XML或者注解搞定,开发到后期,定时任务越来越多,xml配置显得特别臃肿,注解也显得也别繁琐。为了减少重复造轮子,减少代码高度冗余,我们使用Quartz 来统一管理定时任务。
- 引入所需jar
<!-- Quratz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
<exclusions>
<exclusion>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
</exclusion>
</exclusions>
</dependency>
- 添加配置
@Configuration
public class ScheduleConfig {
/**
* 解决Job中注入Spring Bean为null的问题
*/
@Component
public class QuartzJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
//调用父类的方法
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
/**
* 注入scheduler到spring
* @param quartzJobFactory
* @return
* @throws Exception
*/
@Bean
public Scheduler scheduler(QuartzJobFactory quartzJobFactory) throws Exception {
SchedulerFactoryBean factoryBean=new SchedulerFactoryBean();
factoryBean.setJobFactory(quartzJobFactory);
factoryBean.afterPropertiesSet();
Scheduler scheduler=factoryBean.getScheduler();
scheduler.start();
return scheduler;
}
}
/**
* 任务执行器,启动完成后开始执行
*/
@Component
public class ScheduleJobRunner implements ApplicationRunner {
@Autowired
private ScheduleJobService scheduleJobService;
@Autowired
private ScheduleManage scheduleManage;
/**
* 项目启动时重新激活启用的定时任务
* @param applicationArguments
* @throws Exception
*/
@Override
public void run(ApplicationArguments applicationArguments){
List<ScheduleJob> scheduleJobs = scheduleJobService.findByIsPauseIsFalse();
scheduleJobs.forEach(scheduleJob -> {
scheduleManage.addJob(scheduleJob);
});
}
}
- 任务实体
@Data
public class ScheduleJob extends Model<ScheduleJob> {
public static final String JOB_KEY = "JOB_KEY_";
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 定时器名称
*/
private String jobName;
/**
* Bean名称
*/
private String beanName;
/**
* 方法名称
*/
private String methodName;
/**
* 参数
*/
private String params;
/**
* cron表达式
*/
@NotBlank
private String cronExpression;
/**
* 状态 1:正常,0:暂停
*/
private Integer isPause;
/**
* 备注
*/
private String remark;
/**
* 创建日期
*/
private LocalDateTime createTime;
/**
* 更新日期
*/
private LocalDateTime updateTime;
}
- 任务管理器
@Slf4j
@Component
public class ScheduleManager {
private static final String JOB_NAME = "TASK_";
@Resource
private Scheduler scheduler;
public void addJob(ScheduleJob scheduleJob){
try {