配置文件读取cron表达式,启动定时任务
定时任务开关关键点(获取系统配置文件参数后添加:-)
@Scheduled(cron = "${cron:-}")
首先配置文件添加@Scheduled注解所需的cron表达式,
#系统参数 如果不启用,直接删掉即可 每个5秒 */5 * * * * ? 每日凌晨:0 0 0 * * ?
platform.parameters.scheduling.tableDataMigration: */5 * * * * ?
其次,在启动类上添加启用定时任务调度
@Slf4j
@SpringBootApplication
@EnableScheduling // 启用(定时)调度
public class ExamsystemApplication {
public static void main(String[] args) {
SpringApplication.run(ExamsystemApplication.class, args);
log.info(">>>>>>>>>>>>>>>>>>>>>>>>服务启动完成>>>>>>>>>>>>>>>>>>>>>>>");
}
}
然后,添加我们的定时任务类
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* spring-boot启用一个定时任务 并调用配置文件控制所定时长
*
* @author water
* @date 20200427
*/
@Slf4j
@Component // 添加组件
public class TaskSchedulered {
/**
* 定时任务:图片比对记录表迁移
*
* @author: water
* @date: 2020/12/9 16:49
*/
//@Scheduled(cron = "${platform.parameters.scheduling.tableDataMigration}")
//定时任务如果配置就不启动的方法改为为 @Scheduled(cron = "${platform.parameters.scheduling.tableDataMigration:-}")
@Scheduled(cron = "${platform.parameters.scheduling.tableDataMigration:-}")
public void tableDataMigration() {
log.info(">>>>>>>>>>>>>>>>>>定时任务开始执行");
log.info(">>>>>>>>>>>>>>>>>>定时任务执行结束");
}
}
之后,启动项目就会发现我们的项目已经开始执行了
调试任务调度器开关
我们将配置文件的cron表达式整个注释掉或者删掉
#系统参数 如果不启用,直接删掉即可 每个5秒 */5 * * * * ? 每日凌晨:0 0 0 * * ?
#platform.parameters.scheduling.tableDataMigration: */5 * * * * ?
启动项目后,项目无报错,且无任务调度
参考文章:https://stackoverflow.com/questions/58521677/conditionalonproperty-with-scheduled-is-not-working