日常开发中,我们需要对 Spring Boot 定时任务根据环境配置开关。比如测试环境开启,Dev 或本地开发环境关闭。
以下整理4种方法供参考。
准备工作
application.yml 配置定义 jobs 变量
# mangobeta.com application.yml
jobs:
enabled: true
1.Boolean 变量标识
根据 jobs enabled 值做判断,这种缺点是需要在逻辑层判断,而且实际上定时任务已经执行了,只是没有执行业务逻辑而已,不推荐。
@Component
@EnableScheduling
public class ScheduledJobs {
@Value("${jobs.enabled:true}")
private boolean isEnabled;
@Scheduled(fixedDelay = 60000)
public void cleanTempDirectory() {
if(isEnabled) {
// do work here
}
}
}
2.@ConditionalOnProperty
另一种方法使用 Spring 提供的 @ConditionalOnProperty 注解,这种方式没有代码侵入性,配置也简单,比较推荐。
@Component
@EnableScheduling
@ConditionalOnProperty(prefix = "jobs", name = "enabled", havingValue = "true")
public class ScheduledJobs {
@Scheduled(fixedDelay = 60000)
public void cleanTempDirectory() {
}
}
}
3.Spring 配置注解
除了上面2种方式外,使用 @Profile 环境配置方式来控制定时任务开关,也是不错的选择。
@Profile("prod")
@Bean
public ScheduledJob scheduledJob() {
return new ScheduledJob();
}
4.Cron表达式中的值占位符
使用 Cron 表达式中的值占位符控制定时任务开关, 这种方式不太推荐,了解下即可。
@Scheduled(cron = "${jobs.cronSchedule:-}")
public void cleanTempDirectory() {
// do work here
}