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: 6~15 in a cron field picks a random minute, if your cron is cronie

Cron
~/tips/tip-cron-tilde-random-minute

6~15 3 * * * /usr/local/bin/sync-things.sh

Lets a cronie crontab pick a random minute in a range so many machines do not start at once.

When several machines download updates or run a backup at exactly 03:00, they all hit the same server at the same second. Cronie has a small trick that spreads them out.

The crontab(5) manual of cronie describes a randomization syntax: a range written with a tilde instead of a hyphen. A random number within that range is picked, and the range is inclusive. For the minutes field, 6~15 means a random minute between 6 and 15:

6~15 3 * * * /usr/local/bin/sync-things.sh

You can leave out one or both numbers. A lone ~ in the minutes field picks a random minute from 0 to 59. The first number has to be less than or equal to the second.

The important part is when the random number is chosen. The manual says it is picked when the crontab file is parsed. That means the job does not run at a different minute every day. It runs at the same random minute every day, until cron reads the file again. If you want a new draw, edit the crontab.

There is also a crontab variable, RANDOM_DELAY, which delays job startups by a random number of minutes up to the value you give. The manual says its scaling factor is decided when the cron daemon starts and stays constant for the whole run time of the daemon, so the same limit applies.

RANDOM_DELAY=30
0 3 * * * /usr/local/bin/sync-things.sh

The caveat is that this is a cronie feature. On a cron that does not know the syntax, a ~ in a time field may be rejected or ignored, and I did not verify what the Debian and Ubuntu cron does with it. Check man 5 crontab on the machine first, and run crontab -l after saving to see that the line was accepted. For a few of my own machines I would rather use fixed, different minutes than depend on this.

Further reading: crontab(5) manual (cronie)

Going deeper: Guide: find out why a Linux service failed, with journalctl

More Cron tips echo 'systemctl restart myapp' | at 03:00 tomorrow 55 23 28-31 * * [ "$(date -d tomorrow +\%d)" = 01 ] && /usr/local/bin/month-end.sh EDITOR=nano crontab -e 30 6 * * mon /usr/local/bin/weekly-report.sh @daily /usr/local/bin/backup.sh All Cron tips (32) All topics

Link