Site icon perkinstuff.com

Run A Cron Job With A ‘Random’ Time Interval

Here’s an interesting little Linux cron timing trick I found.

For one reason and another, I had a requirement to run a test cron job but with irregular timing to simulate the real scenario of users connecting irregularly.

The trick is to run the cron job on a normal regular interval, but then introduce a pause before it delivers the payload. So in the example below, the job runs every 10 minutes but pauses between 0 and 590 seconds. Thus making it appear semi-random.

First create a simple bash shell script, in say /home/me/demo.sh:

#!/bin/bash
sleep $(($RANDOM%590))s
echo "Hi this email was sent at ${CURRENTDATE}"

The second line tells the script to wait for a random amount of time between 0 and 590 seconds.

It’s important to note that 590 seconds is slightly less than the 10 minute (600 seconds) interval we use in the crontab below which gives a maximum of 10 seconds before the next job starts. Unless you specifically want overlapping jobs, then it’s a good idea to adjust this to allow enough time for each job to complete before the next one!

Next, edit your crontab file:

crontab -e

And add the lines:

MAILTO="<email@domain.tld>"
10 * * * * * bash /home/me/demo.sh

This will run the script and send an email at a random time every 10 minutes or so.

Obviously, you can add your own commands as required.

And as a Brucie bonus, note the MAILTO= setting on the first line. If you ever wondered how to get email notifications from your cron jobs, this is one simple way that will send all of the output created by the job to the email address configured!

Or you can suppress any emails by setting it to MAILTO=””.

And anyway that’s it! Happy cron-ing!


Found This Useful?

If you have found this useful, why not help to support the site and buy me a coffee or perhaps a cheeky beer? Thanks!

Websites Built For You

You may also like Websites Built For You which focuses on web design and development in WordPress, PHP and Javascript.

Exit mobile version