EN VI

Java - Set cron schedule from properties file rather than hard coding it and still avoid Attribute value must be constant?

2024-03-12 01:00:05
How to Java - Set cron schedule from properties file rather than hard coding it and still avoid Attribute value must be constant

I'm using SchedulerLock to create a schedule in my Spring Boot application. Currently the schedule is hard coded to run every 3 hours:

private final String everyThreeHours = "0 0 */3 * * *";

@Scheduled(cron = everyThreeHours)
public void runCleanupSchedule() throws IOException {
    ...
}

I'd like to make everyThreeHours dynamic so I can have different schedules in the properties file for each environment. Unfortunately when I put this in the properties file I get Attribute value must be constant. Is there any way I can set this in my properties rather than having it hard coded?

Solution:

this should work

@Scheduled(cron = "${scheduled.everyThreeHours}")
public void runCleanupSchedule() throws IOException {
    ...
}

in your application.properties add scheduled.everyThreeHours

scheduled.everyThreeHours=0 0 */3 * * *

and you can change the value for each environment properties file

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login