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 youhow to randomize the time a cronjob runs in /etc/cron.d/

If you like this article, consider sponsoring me by trying out a Digital OceanVPS. 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 theinstallation, a cronjob was placed and later the time was randomized between00:00 AM and 06:00 AM. This way the load on the backup targets wouldn't be ahuge 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 usernamebetween the time and executable):

#!/bin/bashRANDM RANDH * * * root /usr/local/bin/my_binary

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

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

# use awk to get a number between 0 and 6 for the hourRANDH="$(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 userecho "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