简体   繁体   English

spring boot scheduling在方法级别启用/禁用任务

[英]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/ . 我按照本指南开始在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). 我想在同一个类中为不同的任务添加更多方法,想知道是否可以通过属性和@ConditionalOnProperty启用/禁用方法级别的任务,似乎@ConditionalOnProperty适用于类级别,而不是方法级别(根据下面的代码示例,这不起作用)。 Any alternative approaches? 任何替代方法? Or have to create another class including task two in order to disable/enable them separately? 或者必须创建另一个类,包括任务2,以便单独禁用/启用它们?

@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). 您可以将@ConditionalOnProperty应用于方法和类型,但似乎这仅适用于注册Bean的方法(请参阅@Conditional文档)。

You should create separate Beans where you can control registration with @ConditionalOnProperty and then apply the @Scheduled annotation to a method within the Bean. 您应该创建单独的Bean,您可以使用@ConditionalOnProperty控制注册,然后将@Scheduled注释应用于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: application.properties:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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