davo777
davo777

Reputation: 336

Using parameters with a spring @Scheduled expression

I'm trying to paramaterize a cron expression currently used for a Spring @Scheduled expression. All other variables coming from the client configuration seem to be loaded correctly for other variables, but Spring doesn't seem to be able to pick up anything in the cron expression.

I've tried a variety of different ways of doing it but none seem to work. Throwing errors like

java.lang.IllegalStateException: Encountered invalid @Scheduled method 'importData': Could not resolve placeholder 'cronExpression' in value "${cronExpression}"

I've tried calling the expression directly from the config file

@Scheduled(cron = "${my.cron.expression}")
    public void importData() {

using the @Qualifier and giving it a direct string name

@Qualifier("cronExpression") String cronExpression
this.cronExpression = cronExpression
...
@Scheduled(cron = "${cronExpression}")
    public void importData() {

but these all still return the above error message

In the client config class, I'm currently trying to import the variable like this:

    @Bean
    @Qualifier("cronExpression")
    public String cronExpression(@Value("${my.cron.expression}") String cronExpression) {
        return cronExpression;
    }

Aside from names, this is the code I'm using which is still throwing an unresolved placeholder error: Properties:

my:
  cron:
    expression: 0 0 4-6 * * *

ClientConfig:

    @Qualifier("cronExpression")
    public String cronExpression(@Value("${my.cron.expression}") String cronExpression) {
        return cronExpression;
    }

Scheduler:

private final String cronExpression;
...
@Qualifier("cronExpression") String cronExpression
...
this.cronExpression = cronExpression
...
@Scheduled(cron = "${cronExpression}")

Upvotes: 0

Views: 3189

Answers (1)

Paolo De Dominicis
Paolo De Dominicis

Reputation: 1425

Here's my Spring Java class:

@EnableScheduling
@SpringBootApplication
@Slf4j
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Scheduled(cron = "${my.cron.expression}")
    public void test(){
        log.info("hello!");
    }
}

And here's my application.yml configuration file:

my.cron.expression: 0 */1 * * * ?

With this configuration, my log is triggered every minute.
(I haven't added particular dependencies)


NOTE

Be careful with the String wrapping of your property: try to unquote it, if Spring gives you an error.

Upvotes: 1

Related Questions