Home > Net >  Spring Scheduled Job to skip based on certain time range
Spring Scheduled Job to skip based on certain time range

Time:03-18

I currently have a spring scheduled job as below which needs to run based on cron expression and it works fine as expected.

@Scheduled(cron = "0 */10 * * * *")
public void myJob() {
   //actions
}

Question:

Now I want to include a check if the cron job runs during a predetermined and configurable time period. If yes, skip the processing.. For example, I want the main cron job to be skipped for 1 hour, between Sunday 8:30AM to 9:30AM.

@Scheduled(cron = "0 */10 * * * *")
public void myJob() {
   if(current time is sunday 8.30AM to 9.30AM){
      return;
   }
}

My thought was to use 2 cron expression to denote start and end values. But not sure how to implement the verification.

private String startCronExpression = "0 30 8 * * 7";
private String endCronExpression = "0 30 9 * * 7";

Any thoughts or help would be appreciated.

CodePudding user response:

To run the job all days but not in a specific time, it is possible to write the range of hours wanted : Example : @Scheduled(cron = "0 */10 0-7,9-0 * * *")

CodePudding user response:

Cron expression supports lists, so you can just try this:

0 */10 0-7,9-23 * * *
  • Related