147

I need the ability to run a PHP script 20 times a day at completely random times. I also want it to run only between 9am - 11pm.

I'm familiar with creating cron jobs in linux.

1
  • 3
    The question is not very well posed. Ultimately you want to distribute 20 points on the time axis between 9am and 11am. But are there constraints on the minimum time difference? Is doing nothing between 9am and 10:30am acceptable? The only way to do this acceptably seems to Klaus' idea: select your 20 times at 09:00, which allows you to fulfill any constraints you might have, then schedule things with "at". Commented Oct 14, 2013 at 19:27

15 Answers 15

195

How to cron something at a random offset 20 times a day between 9am and 11pm? That's kinda tricky within cron, because you are dividing 14 hours by 20 execution times. I don't like the other answers very much because they require writing a bash wrapper script for your php script.

However, if you'll allow me the liberty to ease the timing and frequency restriction to 13 times between 8:30am and 11:09pm, this might do the trick, and all within the confines of your crontab:

30 8-21/* * * * sleep ${RANDOM:0:2}m ; /path/to/script.php

${RANDOM:3:2} uses bash's $RANDOM that other people have mentioned above, but adds bash array slicing. Since bash variables are untyped, the pseudo-random signed 16-bit number gets truncated to the first 2 of its 5 decimal digits, giving you a succinct one-liner for delaying your cronjob between 10 and 99 minutes (though the distribution is biased towards 10 to 32).

The following might also work for you, but I found it do be "less random" for some reason (perhaps Benford's Law is triggered by modulating pseudo-random numbers. Hey, I don't know, I flunked math... Blame it on bash!):

30 8-21/* * * * sleep $[RANDOM\%90]m ; /path/to/script.php

You need to render modulus as '%' above because cron (well, at least Linux 'vixie-cron') terminates the line when it encounters an unescaped '%'.

Maybe you could get the remaining 7 script executions in there by adding another line with another 7-hour range. Or relax your restriction to run between 3am and 11pm.

9
  • 4
    I like the late answer. But if you're trying to generate a random integer evenly distributed in the range of 10 to 99, and the output of RANDOM is 0 to 32,767, why wouldn't you just do $[(RANDOM/368)+10]?
    – jsdalton
    Commented May 2, 2013 at 16:24
  • 4
    @jsdalton: Wouldn't the modulo operator be better? $((RANDOM % 90 + 10)) Test: for i in {0..9999}; do echo $((RANDOM % 90 + 10)); done | sort | uniq -c
    – geon
    Commented Sep 17, 2014 at 8:50
  • 6
    On many systems cron does not use bash by default so it could be better to avoid the bashism $RANDOM: sleep $(( $(od -N1 -tuC -An /dev/urandom) \% 90 ))m. Commented Jun 18, 2015 at 13:57
  • 13
    Make sure that crontab is using bash before you use $RANDOM. If you have vixie-cron (seems to be my case on Ubuntu), then you can add SHELL=/bin/bash to the top. There are more alternatives for other cron versions here: superuser.com/a/264541/260350
    – DaAwesomeP
    Commented Jul 10, 2015 at 23:16
  • 1
    When I use the first suggestion above, I get crontab: errors in crontab file, can't install. Do you want to retry the same edit? please help
    – Sean H
    Commented Sep 13, 2015 at 18:04
102

So I'm using the following to run a command between 1AM and 330AM

0 1 * * * perl -le 'sleep rand 9000' && *command goes here*

That has been taking care of my random needs for me. That's 9000 seconds == 150 minutes == 2.5 hours

4
  • 16
    ::MindBLOWN:: another obscure place to use a little bit of perl. Commented Mar 14, 2018 at 20:55
  • 2
    This is definitely the cleanest answer Commented Jan 23, 2020 at 20:47
  • This is kind of inefficient though, as you are creating a lot of processes. Commented Aug 23, 2020 at 13:21
  • Ruby (Perl's baby) is also a short and nice solution if you don't have perl installed ruby -e 'sleep rand 900'
    – Ulysse BN
    Commented Sep 22, 2023 at 13:23
45

If I understand what you're looking for, you'll need to do something a bit messy, like having a cron job that runs a bash script that randomizes the run times... Something like this:

crontab:

0 9 * * * /path/to/bashscript

and in /path/to/bashscript:

#!/bin/bash

maxdelay=$((14*60))  # 14 hours from 9am to 11pm, converted to minutes
for ((i=1; i<=20; i++)); do
    delay=$(($RANDOM%maxdelay)) # pick an independent random delay for each of the 20 runs
    (sleep $((delay*60)); /path/to/phpscript.php) & # background a subshell to wait, then run the php script
done

A few notes: this approach it a little wasteful of resources, as it fires off 20 background processes at 9am, each of which waits around for a random number of minutes (up to 14 hours, i.e. 11pm), then launches the php script and exits. Also, since it uses a random number of minutes (not seconds), the start times aren't quite as random as they could be. But $RANDOM only goes up to 32,767, and there are 50,400 seconds between 9am and 11pm, it'd be a little more complicated to randomize the seconds as well. Finally, since the start times are random and independent of each other, it's possible (but not very likely) that two or more instances of the script will be started simultaneously.

4
  • 2
    You can make the arithmetic assignments more readable by dropping the dollar sign and moving the double parens to the left (e.g. ((maxdelay = 14 * 60)) or ((delay = $RANDOM % maxdelay))). The sleep argument still needs to be the way you have it (although you could add spaces, if desired). Commented Jan 29, 2012 at 15:41
  • 1
    This worked for me too. My custom bash script looks like below sleep $[ ( $RANDOM % 60 ) + 1 ]s && some_script.sh Commented Mar 7, 2017 at 1:07
  • Am I missing something or the maximum delay should be set to maxdelay=$((14*60/20))
    – Jenish
    Commented Oct 23, 2019 at 4:34
  • @jenishSakhiya The random delays for each of the 20 runs is absolute (well, starting at 9am), not relative to another of the runs. That is, if one of the random delays comes up as 13 hours, that means it'll run at 10pm (13 hours after 9am), not 13 hours after any of the other runs. Commented Oct 23, 2019 at 4:57
32

Some cron implementations offer a RANDOM_DELAY variable.

The RANDOM_DELAY variable allows delaying job startups by random amount of minutes with upper limit specified by the variable.

See crontab(5) for details.

This is seen commonly in anacron jobs, but also can be useful in a crontab.

You might need to be careful with this if you have some jobs that run at fine (minute) granularity and others that are coarse.

7
  • I would love to use the RANDOM_DELAY variable, but can't find any hint in the manpage of crontab(5) on Ubuntu 14.04.4 LTS.
    – Exocom
    Commented Oct 19, 2016 at 12:51
  • That's unfortunate. I wonder if it's not supported there. I see it documented in that manpage on Centos 7 and Arch Linux. Commented Oct 19, 2016 at 17:21
  • 11
    this seems like the correct answer but can you put an example?
    – chovy
    Commented Apr 13, 2017 at 7:21
  • 16
    Please note that RANDOM_DELAY is established once and remains constant for the whole runtime of the daemon. Commented May 14, 2017 at 11:23
  • 16
    The RANDOM_DELAY flag is feature of cronie-crond while Ubuntu seems to be running vixie-cron which lacks this flag.
    – kravietz
    Commented Jul 18, 2019 at 8:00
11

I ended up using sleep $(( 1$(date +%N) % 60 )) ; dostuffs (compatible with bash & sh)

The 1 prefix is to force NON base 8 interpretation of date +%N (e.g. 00551454)

Do not forget to escape % using \% in a crontab file

* * * * *  nobody  sleep $(( 1$(date +\%N) \% 60 )) ; dostuffs 
2
  • 2
    If someone wonders, like me: %N provides current nanos, but some man pages are lacking information for it. This is a very clever solution for people which just need "some randomness" easily per command. Commented Mar 18, 2016 at 14:05
  • 1
    Apart from the caveats already covered elsewhere, this will only work if you have GNU date (which you probably do on most Linuxes, but not on Busybox, standard MacOS, or various other BSD-derived platforms).
    – tripleee
    Commented May 4, 2020 at 12:29
7

My first thought would be to create one cron job launching 20 randomly scheduled at jobs. The at utility (http://unixhelp.ed.ac.uk/CGI/man-cgi?at) is used for executing commands at specified time.

1
6

al-x 's Solution does not work for me since crontab commands are not executed in bash but in sh I guess. What does work is:

30 8 * * * bash -c "sleep $[RANDOM\%90]m" ; /path/to/script.py
2
  • I tried everything and it still didn't work for me. You post explained why, thanks!
    – marlar
    Commented Mar 10, 2020 at 16:45
  • 1
    $[ ... ] is deprecated syntax since waaaay back; for anything from this millennium, you would prefer $((RANDOM\%90))m which is POSIX-compatible syntax (but of course RANDOM is still Bash only).
    – tripleee
    Commented May 4, 2020 at 12:31
5

You can try with this example to use random times before execute command:

#!/bin/bash
# start time
date +"%H:%M:%S"

# sleep for 5 seconds
sleep $(shuf -i 1-25 -n 1)
# end time
date +"%H:%M:%S"
3

at -f [file] [timespec]

or

echo [command] | at [timespec]

or

at [timespec] ... and interactive specification like script's recording.

Command

At runs the text provide on stdin or in the file specified by -f [file].

Timespec

Here's the [timespec] grammar. It can be something like:

  • 24-hour time as 4-digit int, e.g. 0100, 2359, 1620
  • now + 10 minutes
  • 2071-05-31 - 5 hours 12 minutes UTC

If you're explicitly specifying the timezone, some versions of the timespec might only allow UTC for the optional timezone argument.

Example

cat script.sh | at now + $(($RANDOM % 10)) hours $(($RANDOM % 60)) minutes

at -f script.sh now + $(($RANDOM % 10)) hours $(($RANDOM % 60)) minutes

Try it out...

You can test the bash parsing by pre-pending echo and escaping the | (pipe).

echo cat script.sh \| at now + $(($RANDOM % 10)) hours $(($RANDOM % 60)) minutes

echo at -f script.sh now + $(($RANDOM % 10)) hours $(($RANDOM % 60)) minutes

To see jobs scheduled, use atq and job contents (environment vars, setup, and command/script) with at -c [jobid].

Note

The system is part of cron, and the interactive prompt actually captures the whole current state of your shell, so you can run commands without specifying absolute paths.

3

I realize it's an older thread, but I want to add one random-value related thing that I use a lot. Instead of using the $RANDOM variable with a fixed and limited range, I often make arbitrary-range random values in the shell with

dd if=/dev/urandom bs=4 count=1 2>/dev/null | od -N4 -t u4 -A none

so you can do, for example,

FULLRANDOM=$(dd if=/dev/urandom bs=4 count=1 2>/dev/null | od -N4 -t u4 -A none)

and overcome some the restrictions that were discussed in this thread.

2
  • 1
    Welcome to SO. Well, old thread or not, this sent me off to ~$info dd and I can understand what's going on on the left side of |, but can't make out the right side. So, for me and others interested in overcoming some restrictions in random value generation, why not take a moment to explain the RHS, and make a stronger pitch for using your approach. The depth of explanation both makes people comfortable with the process you suggest and its benefits Thanks.
    – Chris
    Commented Jul 18, 2020 at 18:14
  • 2
    Ah ok. od aka "octal dump" takes a file or stdin and dumps the binary data in human-readable form. We want our number shown as an unsigned decimal (-t u4), and don't want the address index (-A none). The -N4 is redundant as we take only 4 bytes, but doesn't hurt either. I hope this explains it...
    – MLP
    Commented Jul 19, 2020 at 5:13
2

What about creating a script that rewrites the crontab every day?

  1. Read current crons (A)
  2. Pick random times (B)
  3. Rewrite prior crons (A), add new random crons (B)
  4. Make sure to add to the cron to run this script in the first place.
4
  • 2
    Don't circumvent the reputation system by posting comments as answers. Your comment does however look good enough to actually be an answer. I recommend removing "I don't have rep to add a comment, but".
    – Ted Lyngmo
    Commented Jun 17, 2020 at 18:55
  • 1
    I just reviewed this answer and missed the part where you're asking a question in return at the end (sloppy work on my part). Don't ask questions in answers. Post your own question for questions you have. I made your semi-question into something that could pass for an answer.
    – Ted Lyngmo
    Commented Jun 17, 2020 at 18:57
  • 1
    Got it! Thx. I'll be more careful next time, no ill intent was meant. Commented Jun 17, 2020 at 22:12
  • 2
    I'm sure you had no ill intent and you don't need to be overly careful. You outlined a possible solution - and stumbled a bit at the end. No worries!
    – Ted Lyngmo
    Commented Jun 17, 2020 at 23:25
1

I was looking for the same problem, for me the best solution was to create a schedule on the server side (it's very simple by means of a programming language), populate a db table with these tasks with two columns: run_time and status (new | processed). So my cron runs every minute and finds jobs that need to be done (status = new and running time <= now()). Very simple and there is one huge plus: in this case I can make an interface for it and see what happens...

0

As it's not mentioned by now, I will show another clean way: Using 'jot'

jot comes on every BSD unix (available as athena-jot in many linuxes, too) and is a sequential and random(!) number generator like seq but easier and more powerful. This simple command:

sleep $(jot -nr 1 1 3600); scriptname

in your crontab executes 'scriptname' after a delay of 1 to 3600 seconds of sleep.

jot -nr 1 1 360

means: give one (first 1) random (-r) number without newline (-n) in the range of one (second number - here 1) and 3600 (third number - here 3600) Clean syntax.

0

Most (if not all) answers so far involve some sort of sleeping a random time and then executing the command. While this works, this creates unnecessary long running processes and can lead to dropped executions (e.g. if a machine restarts during the sleep time), so I was looking for ways to come to the same result without the sleeping part. Further, I wanted to have a cron-only-solution, avoiding doing any calculations in external scripts, or updating the crontab itself dynamically (e.g. regenerate every midnight with new randomness), like a couple answers proposed.

I will first give a way to do exactly what the OP asks, but in addition also some other similar situations (since this is an old question, most people come here by searching for ways to run a cron job at random times, and there can be a couple different interpretations/requirements to that):

Execute a job exactly N times within a specific time range each day

This is exactly what the OP was asking, run the job 20 times each day between 9am and 11pm.

The idea here is to generate (predictable and different each day) a list of N unique timestamps (minute accuracy) in the required interval, and only run the job if the current minute matches one of these timestamps. In order to avoid generating files with this list, the generation happens every time (minimal extra work every minute, with the benefit of having everything self-contained in the crontab).

This is the actual crontab line for this specific situations (20 times between 9am and 11pm), with the explanation below:

* * * * * /bin/bash -c 'h=$(date +\%-H); m=$(date +\%-M); shuf -i $((9*60))-$((23*60)) -n 20 --random-source=<(date +salt.\%Y\%m\%d | sha512sum | xxd -p -r) | grep -q ^$((h*60+m))$' && actual_command

Here:

  • The /bin/bash -c is needed, because bash may not be the default shell in which the cron jobs run, and in this case we need bash because of the process substitution <(...).
  • shuf -i $((9*60))-$((23*60)) -n 20 generates a list of 20 timestamps (minutes since midnight) between 9am (9*60) and 11pm (23*60)
  • We need the output of shuf to be predictable the same each day, otherwise every minute a different list would be generated and that would break the whole concept. For this we use the --random-source.
  • In order to avoid generating a file, we use process substitution from bash (<(...)), and the random source is generated by date +%Y%m%d | sha512sum | xxd -p -r. This generates a hex string that is unique based on the date, the sha512 hash of the date, and xxd transforms this to actual bytes.
  • In the above date command I added a salt. prefix, since this may be needed for separate jobs that should not be synchronized, and in that case we can use a different salt for each job leading to different lists. In addition to the salt, I have sometimes used something like $(hostname) so that I can have the same crontab on different servers, but the tasks not being synchronized.
  • h and m are defined in the beginning as the current hour and minute, and $((h*60+m)) would be the current minutes since midnight.
  • The combined command means then: (generate a list of timestamps) | (grep current timestamp in that list) && (execute the command if found)

One point to be careful about here, the --random-source in shuf is used as the whole actual randomness and not as some sort of seed, so it should be long enough to be able to generate the requested random numbers (otherwise shuf fails with an error). sha512sum that I used here is long enough for generating up to around 47 random numbers between 1 and 1440. If more numbers are needed, the part inside the process substitution should be replaced by calling sha512sum repeatedly a couple times, e.g. like this:

seq 10 | while read n; do date +salt.$n.\%Y\%m\%d | sha512sum; done | xxd -p -r

Execute a job on average N times within a specific time range each day

This is a more relaxed version of the OP question, where we don't really care if the job is executed exactly N times, but we want an average of N times. For this we can use a poisson process, and decide at each minute independently if we want to run the job or not, with probability N/(number of minutes in the interval):

* 9-22 * * * /bin/bash -c 'test $((RANDOM \% 840)) -lt 20' && actual_command

(840 is the number of minutes between 9am and 11pm, 14*60).

This is obviously much simpler than requiring exactly N runs, and in most real life cases should be sufficient. Here, also bash is needed, this time because of the $RANDOM

Same as above, but predictable

The above works good, but some times during debugging it is beneficial to have predictable randomness (did the job fail silently, or did it just not run for the last half hour because the random condition didn't trigger?).

This can be done similar to above, but instead of $RANDOM use some hash based on the current time (with minute accuracy), like this:

* 9-22 * * * x=$(printf "\%d" 0x$(date +salt.\%Y\%m\%d\%H\%M | md5sum | head -c8)); test $((x \% 840)) -lt 20 && actual_command

Here:

  • date +salt.%Y%m%d%H%M | md5sum | head -c8 gives a predictable pseudorandom 8-character hexadecimal number (the first 8 characters of the md5sum) based on the current minute.
  • printf "%d" 0x(...) transforms this into a decimal number.
  • After that, the test is the same as above, modulo 840 (number of minutes in the required interval) and checking for less than 20 (average number of executions per day we need.
  • This time, everything works with the standard shell, no bash is needed.

A different way for this situation, short, but kind of a hack and not as flexible is something like this:

* 9-22 * * * case "$(date +salt.\%Y\%m\%d\%H\%M | md5sum)" in 00*|01*) actual_command;; esac

This gets executed whenever the md5sum of the current time starts with 00 or 01, this has a probability of 2/256 or in other words happens on average once every 128 minutes. For other requirements we have to adapt what prefixes we want to allow, e.g. for 4/256 or around once per hour: ... in 0[0-3]*). The check can get more complicated by combining 2-, 3-character and possibly longer prefixes to generate more precise probabilities, e.g. something crazy like this: ... in 0[0-5]*|06[0-9a-c]*|06d[0-3]) (giving probability 0x6d4/0xffff, or on average one run every 0xffff/0x6d4=37.5 minutes). But in all seriousness, I would not recommend anybody to go this far, I would rather go back to using the first option in this case. But for simple 16-based ratios, like once every 256 minutes (around 4 hours), I would possibly prefer this for being compact.

Special case, exactly once per day at a random time

This is a special case of the OP needing exactly N times in specific interval. Since we want only one random number (minutes since midnight) here, we can get that easier than using shuf like in the first case (and no need for bash again).

* * * * * h=$(date +\%H); m=$(date +\%M); x=$(printf "\%d" 0x$(date +salt.\%Y\%m\%d | md5sum | head -c8)); test $((x \% 1440)) -eq $((60*h+m)) && actual_command

Here, x will be again a predictable (every day different) random number, and the test checks if the current minute (since midnight) is equal to the random number modulo 1440 (number of minutes in a day).

We can similar to above restrict the interval in this case, e.g. like this (again for the interval 9am to 11pm):

* * * * * h=$(date +\%H); m=$(date +\%M); x=$(printf "\%d" 0x$(date +salt.\%Y\%m\%d | md5sum | head -c8)); test $((540 + x \% 840)) -eq $((60*h+m)) && actual_command

-1

For those who googled the way here:

If you are using anacron (Ubuntu desktop and laptop) then you can edit

/etc/anacrontab

and add

RANDOM_DELAY=XX 

Where XX is the amount of minutes you want to delay the base job.

Anacron is like cron but it does not expect your computer to be on 24x7 (like our laptops) and will run the scripts that it missed because the system was down.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.