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
@Scheduled(fixedDelay = 60000) void doSomeThing(){...}
.
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
:
@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(); } }
In application.yml
, add:
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
(note the cron expression: leaving it empty may prevent SpringBoot from starting)
In application.yml
, add:
jobScheduler: # noinspection GrazieInspection scheduling: type: cron cron: 0 0 1 * * ?
It should work now ;-).