I am trying to automate some things in ubuntu.
A tutorial I followed helped me set up some cron jobs for periodic tasks.
I was curious if there are any tools in cron jobs that would let me select a random time within a time period to do a task? The tutorial didn't mention anything about that.
via cron, no, finest granularity for a cronjob is 1 minute.
One simple scenario - have a job start somewhere between two datetimes would be to have the job start at earliest time, then for there to be a randomised sleep period within the start/stop times and have have the job start after that sleep period expires.
Cron jobs aren't great if you want a fine control over the tasks, you are better off setting up Systemd Timers.
Here's what it might look like:
You can probably find examples of random sleep in files in the /etc/cron.*
directories. Here's an example based on spamassassin:
Create an executable script named randomsleep
like this:
#!/bin/sh
# randomsleep - Sleep for a random number of seconds within a range (default 3600s)
# usage: randomsleep [#]
range=${1:-3600}
sleep $(expr $(od -vAn -N2 -tu4 < /dev/urandom) '%' $range)
Another example (certbot
) uses perl -e 'sleep int(rand(43200))'
.
Then cronjobs can look something like this:
# Run this job at a random time between 1am and 2am
0 1 * * * randomsleep; cmd arg...
bash has $RANDOM
#!/bin/bash
sleep $(( RANDOM % 3600 ))
Save/run this as /path/to/radomsleep
, or put it directly into the crontab:
# Run this job at a random time between 1am and 2am
0 1 * * * bash -c 'sleep $(( RANDOM % 3600 ))'; echo "I am the delayed task"
In cron jobs, you have to escape %
with \
, otherwise it will be converted to newline, see man 5 crontab
.
Ah yes, thanks.
And I think the \
is not removed by cron, so it must be removed by the outer shell:
# Run this job at a random time between 1am and 2am
0 1 * * * bash -c 'sleep $(( RANDOM '\%' 3600 ))'; echo "I am the delayed task"