简体   繁体   中英

spring boot scheduling enable/disable tasks in method level

I am following this guide to start scheduling tasks in spring boot https://spring.io/guides/gs/scheduling-tasks/ .

I want to add more methods for different tasks in the same class, wondering if it is possible to enable/disable the tasks on the method level via the properties and @ConditionalOnProperty , seems @ConditionalOnProperty works on the class level only, not the method level(as per the code example below, which doesn't work). Any alternative approaches? Or have to create another class including task two in order to disable/enable them separately?

@Component    
public class SchedulingTasks {

    private static final Logger log =    LoggerFactory.getLogger(SchedulingTasks.class);

    @Scheduled(fixedRate = 50000)
    public void jobOne() {
        log.info("job one started at {}", LocalDateTime.now());
    }

    @Scheduled(fixedRate = 50000)
    @ConditionalOnProperty(name="job.two", havingValue="true")  
    public void jobTwo() {
        log.info("just two started at {}", LocalDateTime.now());
    }
}

You can apply @ConditionalOnProperty to methods as well as types, but it appears that this only applies to methods that register Beans (see @Conditional documentation).

You should create separate Beans where you can control registration with @ConditionalOnProperty and then apply the @Scheduled annotation to a method within the Bean.

Example:

@Slf4j
@Service
@ConditionalOnProperty(prefix = "schedule", name = {"job.one"}, havingValue = "true")
public class JobOneScheduler {

    @Scheduled(cron = "*/2 * * * * *")
    public void runJob() {
        log.debug( "Running job one... {}", LocalDateTime.now() );
    }
}


@Slf4j
@Service
@ConditionalOnProperty(prefix = "schedule", name = {"job.two"}, havingValue = "true")
public class JobTwoScheduler {
    @Scheduled(cron = "*/5 * * * * *")
    public void runJob() {
        log.debug( "Running job two... {}", LocalDateTime.now() );
    }
}

application.properties:

schedule.job.one=true
schedule.job.two=false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM