SpringBoot中定时任务使用配置文件配置执行时间
在传统的Spring项目中使用Spring Task设置定时任务,其执行时间配置到applicationContext.xml中指定执行方法即可;但是由于现在换做了SpringBoot框架,虽然Spring Task是集成在SpringBoot中的,但是大多是用注解直接把执行之间cron声明在了方法名上,这样不利于生产环境修改执行时间(PS:有尝试使用@Value取值后使用,未果所以换方式)
原spring Task写法:
@Scheduled(cron = "0 0 0/1 * * ?")
public void queryPayStatus() {
logger.info("执行定时任务queryPayStatus---start");
logger.info("执行定时任务queryPayStatus---end");
}
按上述方法模板就创建了一个定时任务的执行方法,cron = "0 0 0/1 * * ?"表时一小时执行一次,具体时间可参考cron表达式。
问题是,我现在想把执行时间放到配置文件中该怎么弄呢?
在application.properties中配置:
custom.cron=0 0 0/1 * * ?
代码如下:
其中 @PropertySource(value="classpath:application.properties",ignoreResourceNotFound=true)
用于spring项目如果你是springboot项目则不用加此注解
@Component
@PropertySource(value="classpath:application.properties",ignoreResourceNotFound=true)
public class AlarmJob {
@Scheduled(cron="${custom.cron}")
public void fetch() {
System.err.println("开始执行");
}
}
注意:springboot对应的定时任务是串行的,如果复杂并行的定时任务不满足。
若需要,请参考 SpringBoot定时任务的几种实现方式 中的多线程执行