Skip to main content

Raymii.org Logo (IEC resistor symbol) logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

Bash Bits: Randomize a cronjob to run between 00:00 and 06:00 hours

Published: 06-05-2019 | Author: Remy van Elst | Text only version of this article


Table of Contents


Bash Bits are small examples and tips for Bash Scripts. This bash bit shows you how to randomize the time a cronjob runs in /etc/cron.d/

If you like this article, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get $100 credit for 60 days). (referral link)

All Bash Bits can be found using this link

Randomize cronjob time

I've used this in the past in a backup script I wrote. During the installation, a cronjob was placed and later the time was randomized between 00:00 AM and 06:00 AM. This way the load on the backup targets wouldn't be a huge peak but more spread out.

First, place your cronjob in /etc/cron.d/, as a file. In this case, /etc/cron.d/my_example. Use the regular cron.d format (include the username between the time and executable):

#!/bin/bash
RANDM RANDH * * * root /usr/local/bin/my_binary

Note the two variables, RANDM and RANDH. These will be replaced to the random hour and minute.

The following code will replace the variables with random digits, but in the range you specify:

# use awk to get a number between 0 and 6 for the hour
RANDH="$(awk 'BEGIN{srand();print int(rand()*(0-6))+6 }')"
# and 0 to 59 for the minutes. 
RANDM="$(awk 'BEGIN{srand();print int(rand()*(0-59))+59 }')"
# Replace it in the cronjob.
sed -i -e "s/RANDH/${RANDH}/g" -e "s/RANDM/${RANDM}/g" /etc/cron.d/my_example
# show the user
echo "Randomized cronjob time, will run on ${RANDH}:${RANDM}."

You could use the bash builtin $RANDOM, but then you cannot specify a range. You could get an illigal time that way.

Tags: bash , bash-bits , command , cron , crontab , random , shell , snippets , time