Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-Boot one @Scheduled task using multiple cron expressions from yaml file

I like to have an implementation of one @Scheduled job using different configuration properties of .ymlfile.

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?

like image 484
Patrick Avatar asked Dec 02 '16 09:12

Patrick


1 Answers

application.yaml:

crontab:  
  submitSubtask: "0 * * * * *"  
  updateBacktrace: "2/30 * * * * *"  

java code:


@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.

like image 152
geekyouth Avatar answered Sep 21 '22 16:09

geekyouth