Search code examples
javacronjob-schedulingquartz

I am trying to pass a variable into a cronSchedule expression function in java


Here is the expression:

int month = 8;
    Trigger trigger1 = TriggerBuilder.newTrigger()
                .withIdentity("cronTrigger1", "group1")
                .withSchedule(CronScheduleBuilder.cronSchedule("0 57 01 14 month ? 2021"))
                .build();

Does any one know how to pass the variable into the .cronSchedule?


Solution

  • You could do

    Trigger trigger1 = TriggerBuilder.newTrigger()
                    .withIdentity("cronTrigger1", "group1")
                    .withSchedule(CronScheduleBuilder.cronSchedule(String.format("0 57 01 14 %s ? 2021", month)))
                    .build();
    

    Although I think using one of the static methods in http://www.quartz-scheduler.org/api/2.2.3/index.html like weeklyOnDayAndHourAndMinute and the DateBuilder constants to make it more readable.