Selecting cron expression for @Scheduled based on another configuration list property in Spring

558 Views Asked by At

The following custom configuration properties exist in my Spring Boot (2.5.4) application:

application.yml

app:
  tasks:
    - name: A
      url: http://server-a
      cron-expression: "*/5 * * * * *"
    - name: B
      url: http://server-b
      cron-expression: "*/10 * * * * *"

Configuration class

@Configuration
@ConfigurationProperties(prefix = "app")
@Getter
@Setter
public class ApplicationConfiguration {

    private List<TaskEntry> tasks;

    @Getter
    @Setter
    public static class TaskEntry {
        private String name;
        private String url;
        private String cronExpression;
    }
}

Now, there is also a method which shall run with the @Scheduled annotation. While specifying a variable expression for the cron argument is easy, I'm looking for a more dynamic apporach.

This cron-expression to be used in the @Scheduled annotation shall be selected by the TaskEntry with name == A. So I came up with something like this:

@Scheduled(cron = "${app.tasks.?[name == 'A'].cron-expression}")
public void run() {
    log.info("Starting task A...");
}

This fails with the following message:

Could not resolve placeholder 'app.tasks.?[name == 'A'].cron-expression' in value "${app.tasks.?[name == 'A'].cron-expression}"

0

There are 0 best solutions below