How to contol all spring batch jobs running as scheduled cron jobs by passing a boolean flag to disable or enable the jobs?

Viewed 288

I have created a job status table where i have a boolean flag based on that i am returning the cron expreesion(active cron or hypen(-) cron) and my scheduler will work. Boolean flag will be updated if you want to enable or disable all spring batch jobs.

How can we contol the flag in the application otherwise we will have issues in running the cron expression?

@Scheduled(cron = "#{@getCronValueDevice}")
@Scheduled(cron = "#{@getCronValueStorage}")

@Bean
public String getCronValueDevice() {
    JobStatus jobStatus = jobStatusRepository.findByJobName(BatchJobConstants.DEVICE_JOB_NAME);
    if (jobStatus != null && jobStatus.getIsActive()) {
        return jobStatus.getActiveCronExpression();
    } else {
        return "-";
    }
1 Answers

If the goal is to enable/disable scheduled jobs using a flag, I would keep it simple and make the job launching code conditioned by that flag, something like:

@Scheduled(cron = "#{your.cron.expression}")
public void runJob() {
   boolean enabled = ... // dynamically load the flag as needed
   if (enabled) {
      // run the job
   }
}

This does not require to change the cron expression on the fly to enable/disable the schedule. When the flag is false, the job will not be executed at subsequent schedules unless it is reactivated again.

BTW, kubernetes provides a similar feature to suspend/resume cron jobs (this can be done on the fly by patching the cron job specification).

Related