要通过.yml配置文件控制所有定时任务的开启或关闭,你可以使用Spring Boot的属性配置功能。
首先,在你的application.yml(或者application.properties)文件中添加一个属性来指示是否开启定时任务,下面是.yml配置,如:
# 是否开启定时任务,默认为true,true为开启定时任务,false则不开启
scheduled:
tasks:
enabled: true
然后,在你的定时任务类中使用@ConditionalOnProperty注解,根据配置的属性值来决定是否启用定时任务。代码如下:
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@EnableScheduling
@ConditionalOnProperty(name = "scheduled.tasks.enabled", havingValue = "true")
public class MyScheduledTasks {
@Scheduled(cron = "0 0 0 * * ?")
public void myTask() {
// 执行定时任务的逻辑
}
}
这样子我们只需要在.yml文件中的控制true开启或false不开启即可