Search code examples
springspring-bootcronscheduled-tasksapplication.properties

How to access Cron expression from application.properties file


This is my job schedule part and I want to remove the cron trigger, CronTrigger("0 40 13 * * ?") then access the cron expression from application.properties.

@Component
public class DynamicjobSchedule  {

    public void schedulejobs() {

        for (ConnectionStrings obj : listObj) {
            System.out.println("Cron Trigger Starting..");
            scheduler.schedule(new DashboardTask(obj), new CronTrigger("0 40 13 * * ?"));
        }
    }
}

How can I create one property file in src/main/resources location and mention the cron expression then call from the scheduler?


Solution

  • The simplest way is to use @Value annotation like this:

    @Component
    public class DynamicjobSchedule {
    
        @Value("${name.of.cron.expression.in.application.properties}")
        private String cronExpression;
    
        public void schedulejobs() {
    
            for (ConnectionStrings obj : listObj) {
                System.out.println("Cron Trigger Starting..");
                scheduler.schedule(new DashboardTask(obj), new CronTrigger(cronExpression));
            }
        }
    }
    

    You can use the @Value annotation on method parameter too:

    @Component
    public class DynamicjobSchedule {
    
        public void schedulejobs(@Value("${name.of.cron.expression.in.application.properties}") String cronExpression) {
    
            for (ConnectionStrings obj : listObj) {
                System.out.println("Cron Trigger Starting..");
                scheduler.schedule(new DashboardTask(obj), new CronTrigger(cronExpression));
            }
        }
    }