Weekdays cron job, but for a particular date range.

Cron is a very simple, yet useful job scheduler on linux.

To schedule a job for weekdays, one can easily do “15 00 * * 1-5” which runs at 0015 UTC for Monday – Friday, since 0 denotes Saturday and 7 denotes Sunday in crontab. However, when we have to work with a particular date range, (eg. 10-15 only) we have to use the following method.

15 00 * * 1-5 [$(date +\%d) > 09 && $(date +\%d) < 16] && /path/to/your/script

Here, we are scheduling the cron for weekdays, but also adding a condition to check the date within to be 10-15.

  • If any of the dates between 10-15 fall on a weekend, then the cron does NOT execute.
  • If any weekdays have dates other than 10-15, the the cron does NOT execute.
  • “15 00 10-15 * 1-5” cron would execute at 0015 hrs every weekday AND everyday between 10-15.

Feel free to test the desired “date” outputs:

$ date +\%d
12
$ echo $[ $(date +\%d) > 10 && $(date +\%d) < 15]
1
$ echo $[ $(date +\%d) > 15 && $(date +\%d) < 20]
0

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s