Shivi Sharma
Shivi Sharma

Reputation: 277

How can I create Cron Expression which works between particular times

I am working on a Cron Expression for a job that has to run on weekdays every 10 mins from 7.30 am to 8.20 am(inclusive).

The trigger used by me:- 0 30/10 7-9 ? * SUN,MON,TUE,WED,THU *

Issue is it works beyond 8.20 as well? Can we limit it to specific minutes or end time? like 7:30-8:20

Upvotes: 0

Views: 255

Answers (1)

kvantour
kvantour

Reputation: 26491

Some things you cannot do in a single expression and you might consider to use two:

# Example of job definition:
# .--------------------- minute (0 - 59)
# |       .------------- hour (0 - 23)
# |       |  .---------- day of month (1 - 31)
# |       |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |       |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |       |  |  |  |
# *       *  *  *  *   command to be executed
# This runs on 7:30, 7:40, 7:50
 30/10    7  *  * 1-5  command
# This runs on 8:00, 8:10, 8:20
 0-20/10  8  *  * 1-5  command

Another way you could attempt this is by using a test.

# Example of job definition:
# .--------------------- minute (0 - 59)
# |      .------------- hour (0 - 23)
# |      |   .---------- day of month (1 - 31)
# |      |   |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |      |   |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |      |   |  |  |
# *      *   *  *  *   command to be executed
*/10    7,8  *  * 1-5  testcmd && command

Where testcmd is an executable script that could look like:

#!/usr/bin/env bash
hours=$(date "+%H")
minutes=$(date "+%M")
(( hours == 7 && minutes >= 30)) || (( hours == 8 && minutes <= 20 ))

Other examples of this trick can be found here:

Upvotes: 1

Related Questions