brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: sleep $((RANDOM % 300)) spreads shell cron jobs over a few minutes

Shell
~/tips/tip-shell-random-cron-delay

sleep $((RANDOM % 300))

Add a random delay so many machines do not hit the same server at once.

If ten machines all run the same cron job at 03:00, they all hit the same update server or backup target in the same second. A small random wait at the start of the script fixes that.

$RANDOM gives a new number from 0 to 32767 each time you read it. The modulo turns it into a range:

#!/usr/bin/env bash
# wait 0 to 299 seconds before starting
sleep $((RANDOM % 300))
restic backup /srv/data

Every run now starts somewhere in the first five minutes after the scheduled time. It costs nothing and you do not need a different crontab per machine.

I also like it in loops that retry something, so two scripts that failed together do not retry together forever.

Keep in mind what it is not. $RANDOM is fine for spreading load, but it is not meant for anything secret like tokens or passwords. It is also bash only: in /bin/sh on Debian or Ubuntu, $RANDOM is empty, the sum comes out as 0 and the script quietly never waits, so make sure the shebang says bash. If you use systemd timers, RandomizedDelaySec= does the same job without touching the script.

Further reading: Bash manual: Bash Variables (RANDOM), systemd.timer manual

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link