Nital
Nital

Reputation: 6084

How to run a job in Spring Boot between 9:30 am to 4:00 pm every 5 mins?

Currently I have the following 2 cron expressions configured in the application but the job runs past 4:00 pm.

As show in the application logs below I see logger statements even after 4:00 pm. Not sure why.

application.properties

#Starts at 9:30 AM and ends at 10:00 AM. Runs every 5 mins
job.cron1=0 30-55/5 9 * * MON-FRI
#Starts at 10:00 AM and ends at 4:00 PM. Runs every 5 mins
job.cron2=0 */5 10-16 * * MON-FRI

PurgeData.java

@Scheduled(cron = "${job.cron1}")
public void purgeDBData1() {
    log.info("Purging DB data every 5 mins between 9:30 am - 10:00 am...");
}


@Scheduled(cron = "${job.cron2}")
public void purgeDBData2() {
    log.info("Purging DB data every 5 mins between 10:00 am - 4:00 pm...");
}

Application Logs:

2021-03-02 16:05:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...
2021-03-02 16:10:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...
...
....
.....
2021-03-02 16:45:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...
2021-03-02 16:50:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...
2021-03-02 16:55:20,801 INFO job.PurgeDataJob [scheduling-1] Purging DB data every 5 mins between 10:00 am - 4:00 pm...

Upvotes: 2

Views: 2923

Answers (2)

Nikolas
Nikolas

Reputation: 44378

You need two crons to handle a start at the half-past nine. The common part is each 5 seconds from Monday to Friday. Remember the latter values are inclusive, so the range must be to 15, which is 3pm.

The hour and minute span differs:

  • 0 30/5 9 ? * MON,TUE,WED,THU,FRI * - where 30/5 9 means every 5 minutes starting at 9:30am only for the 9th hour (so up to 10am, exclusive).
  • 0 0/5 10-15 ? * MON,TUE,WED,THU,FRI * - where 0/5 10-15 means every 5 mintes starting at 10am up to 4pm (exclusive)

You will need to use @Schedules to define nested @Scheduled annotations.

@Schedules ({
    @Schedule(cron = "${job.cron1a}"),       // a cron with 9:30am to 9:59am
    @Schedule(cron = "${job.cron1b}")        // a cron with 10am to 16pm
})
public void purgeDBData1() {
    log.info("Purging DB data every 5 mins between 9:30 am - 10:00 am...");
}

Upvotes: 1

Quang Nguyen
Quang Nguyen

Reputation: 354

You should configure it as following

job.cron2=0 */5 10-15 * * MON-FRI

Upvotes: 2

Related Questions