Posts Tagged ‘SpringBatch’
SpringBatch: How to have different schedules, per environment, for instance: keep the fixedDelay=60000 in prod, but schedule with a Cron expression in local dev?
Case
In SpringBatch, a batch is scheduled in a bean JobScheduler
with
[java]
@Scheduled(fixedDelay = 60000)
void doSomeThing(){…}
[/java]
.
How to have different schedules, per environment, for instance: keep the fixedDelay=60000
in prod, but schedule with a Cron expression in local dev?
Solution
Add this block to the <JobScheduler
:
[java]
@Value("${jobScheduler.scheduling.enabled:true}")
private boolean schedulingEnabled;
@Value("${jobScheduler.scheduling.type:fixedDelay}")
private String scheduleType;
@Value("${jobScheduler.scheduling.fixedDelay:60000}")
private long fixedDelay;
@Value("${jobScheduler.scheduling.initialDelay:0}")
private long initialDelay;
@Value("${jobScheduler.scheduling.cron:}")
private String cronExpression;
@Scheduled(fixedDelayString = "${jobScheduler.scheduling.fixedDelay:60000}", initialDelayString = "${jobScheduler.scheduling.initialDelay:0}")
@ConditionalOnProperty(name = "jobScheduler.scheduling.type", havingValue = "fixedDelay")
public void scheduleFixedDelay() throws Exception {
if ("fixedDelay".equals(scheduleType) || "initialDelayFixedDelay".equals(scheduleType)) {
doSomething();
}
}
@Scheduled(cron = "${jobScheduler.scheduling.cron:0 0 1 * * ?}")
@ConditionalOnProperty(name = "jobScheduler.scheduling.type", havingValue = "cron", matchIfMissing = false)
public void scheduleCron() throws Exception {
if ("cron".equals(scheduleType)) {
doSomething(); }
}
[/java]
In application.yml
, add:
[xml]
jobScheduler:
# noinspection GrazieInspection
scheduling:
enabled: true
type: fixedDelay
fixedDelay: 60000
initialDelay: 0
cron: 0 0 1 31 2 ? # every 31st of February… which means: never
[/xml]
(note the cron expression: leaving it empty may prevent SpringBoot from starting)
In application.yml
, add:
[xml]
jobScheduler:
# noinspection GrazieInspection
scheduling:
type: cron
cron: 0 0 1 * * ?
[/xml]
It should work now ;-).