There are many scheduled tasks @Scheduled(cron = “0 0 0 * * ?”) in Spring Boot. How can I configure it through .yml to control whether all scheduled tasks are enabled or not?

To control the opening or closing of all scheduled tasks through the .yml configuration file, you can use Spring Boot's property configuration function.

First, add a property to your application.yml (or application.properties) file to indicate whether to enable scheduled tasks. The following is the .yml configuration, such as:

# 是否开启定时任务,默认为true,true为开启定时任务,false则不开启
scheduled:
  tasks:
    enabled: true

Then, use the @ConditionalOnProperty annotation in your scheduled task class to decide whether to enable the scheduled task based on the configured property value. code show as below:

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() {
    
    
        // 执行定时任务的逻辑
    }
}

In this way, we only need to control true to turn on or false to turn off in the .yml file.

Guess you like

Origin blog.csdn.net/weixin_44912902/article/details/134973016