Reputation: 25
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());
}
}
Upvotes: 1
Views: 1368
Reputation: 1559
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
Upvotes: 2