14

Is there a way to call a getter (or even a variable) from a propertyClass in Spring's @Scheduled cron configuration? The following doesn't compile:

@Scheduled(cron = propertyClass.getCronProperty()) or @Scheduled(cron = variable)

I would like to avoid grabbing the property directly:

@Scheduled(cron = "${cron.scheduling}")
ltalhouarne
  • 4,586
  • 2
  • 22
  • 31

4 Answers4

12

Short answer - it's not possible out of the box.

The value passed as the "cron expression" in the @Scheduled annotation is processed in ScheduledAnnotationBeanPostProcessor class using an instance of the StringValueResolver interface.

StringValueResolver has 3 implementations out of the box - for Placeholder (e.g. ${}), for Embedded values and for Static Strings - none of which can achieve what you're looking for.

If you have to avoid at all costs using the properties placeholder in the annotation, get rid of the annotation and construct everything programmatically. You can register tasks using ScheduledTaskRegistrar, which is what the @Scheduled annotation actually does.

I will suggest to use whatever is the simplest solution that works and passes the tests.

hovanessyan
  • 30,580
  • 6
  • 55
  • 83
2

If you don't want to retrieve the cron expression from a property file you can do it programatically as it follows:

// Constructor
public YourClass(){
   Properties props = System.getProperties();
   props.put("cron.scheduling", "0 30 9 * * ?");
}

That allows you to use your code whitout any changes:

@Scheduled(cron = "${cron.scheduling}")
J. Saorin
  • 21
  • 3
0
public class CronProperties {

    private String expression;

    public String getExpression() {
        // Logic to dynamically determine the cron expression
        return "0 0 0 * * *";
    }

    public void setExpression(String expression) {
        this.expression = expression;
    }
}

@Autowired
private CronProperties cronProperties;

@Scheduled(cron = "#{cronProperties.expression}")
public void runTaskWithDynamicCronExpression() {
    // Your task logic here
}
-3
@Component
public class MyReminder {

    @Autowired
    private SomeService someService;

    @Scheduled(cron = "${my.cron.expression}")
    public void excecute(){
        someService.someMethod();
    }
}

in /src/main/resources/application.properties

my.cron.expression = 0 30 9 * * ?
R. S.
  • 402
  • 5
  • 17
  • 1
    That is my current code. My question is about using a variable or a getter instead of `${my.cron.expression}` – ltalhouarne Apr 05 '16 at 12:53