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: 9-17/2 in a cron field runs a job every two hours, only during the day

Cron
~/tips/tip-cron-range-with-step

0 9-17/2 * * 1-5 /usr/local/bin/sync-orders.sh

Combines a range and a step in one cron field, for schedules limited to office hours.

A step like */2 means every second value over the whole field. Put a range in front of it and the step only counts inside that range.

0 9-17/2 * * 1-5  /usr/local/bin/sync-orders.sh

The hours field 9-17/2 means: start at 9, then every second hour up to 17. So this runs at 09:00, 11:00, 13:00, 15:00 and 17:00, on weekdays only, because 1-5 in the last field is Monday to Friday. The man page’s own example is 0-23/2 for every other hour.

The step always counts from the start of the range, not from zero. That’s handy: 1-23/2 gives the odd hours and 0-23/2 the even ones. In the minutes field, 5-59/15 runs at :05, :20, :35 and :50, nicely away from the full hour when many other jobs start.

You can also make a list of ranges, separated by commas: 0 8-12/2,14-18/2 * * * skips the lunch hour.

Mind the end of the range. With 9-18/2 the last run is 17:00, because 19 is outside the range, and that can surprise you when you expected 18:00. I’d write out the times the line should hit in a comment above it, so a later reader can check the math.

Further reading: crontab(5) manual page, Debian cron, crontab(5) manual page, 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