I like to have an implementation of one @Scheduled
job using different configuration properties of .yml
file.
Means in my yaml file I describe the cron expression
as a list:
job:
schedules:
- 10 * * * * *
- 20 * * * * *
I read those values out using Configuration and created a @Bean
named scheduled
:
@Configuration
@ConfigurationProperties(prefix="job", locations = "classpath:cronjob.yml")
public class CronConfig {
private List<String> schedules;
@Bean
public List<String> schedules() {
return this.schedules;
}
public List<String> getSchedules() {
return schedules;
}
public void setSchedules(List<String> schedules) {
this.schedules = schedules;
}
}
In my Job class I want to start the execution of one method but for both of the schedules in my configuration.
@Scheduled(cron = "#{@schedules}")
public String execute() {
System.out.println(converterService.test());
return "success";
}
With this solution the application creates an error: (more or less clear)
Encountered invalid @Scheduled method 'execute': Cron expression must consist of 6 fields (found 12 in "[10 * * * * *, 20 * * * * *]")
Is there a way to configure the same scheduled job method with multiple declarations of cron expressions?
EDIT 1
After some try I just used a second annotation on the executer method.
@Scheduled(cron = "#{@schedules[0]}")
@Scheduled(cron = "#{@schedules[1]}")
public String execute() {
System.out.println(converterService.test());
return "success";
}
This solution works but is not really dynamic. Is there also a way to make this dynamic?
crontab:
submitSubtask: "0 * * * * *"
updateBacktrace: "2/30 * * * * *"
@EnableScheduling
public class Demo{
@Scheduled(cron = "${crontab.updateBacktrace}")
private void updateBacktrace() {
...
}
@Scheduled(cron = "${crontab.submitSubtask}")
private void submitSubtask() {
...
}
}
it works for springboot 2.3.7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With