Skip to main content Logo

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

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

❗ This post is over five years old. It may no longer be up to date. Opinions may have changed.

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/

Recently I removed all Google Ads from this site due to their invasive tracking, as well as Google Analytics. Please, if you found this content useful, consider a small donation using any of the options below:

I'm developing an open source monitoring app called Leaf Node Monitoring, for windows, linux & android. Go check it out!

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.

You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $200 credit for 60 days. Spend $25 after your credit expires and I'll get $25!

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):

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