Restart appliance using cron

It may be necessary to restart an appliance, for example a WiFi access point, at a regular time each day. The easiest way to do this is by using a cron job.

# edit crontab
crontab -e
22 4 * * * [ $( awk -F '.' '{print $1}' /proc/uptime ) -gt 43200 ] && reboot
# check contents of crontab
crontab -l
# restart cron service
service cron restart

The cron time / date specification above is 04:22 on any day of the month, any month and any day of the week.

Why is just the reboot command not enough? Although the system time is normally set by ntp, this only happens in the later stages of the boot process, once networking is up and running. Until then time is initially set to an arbitrary fixed value or to the time stamp value of the file in /etc that was last modified. If the latter, the system time may end up being a value close to the cron reboot job time specification. If this happens, the cron job will get executed before the ‘correct’ time is set by ntp resulting in a boot loop. To avoid the boot loop we only execute the reboot command if the system has been up and running for at least 12 hours (hence the value 12*3600=43200 above).

Alternative cron commands could be

22 4 * * * [ $( cat /proc/uptime | cut -d '.' -f 1 ) -gt 43200 ] && reboot

or

22 4 * * * sleep 70 && touch /etc/banner && reboot

Leave a Reply

Your email address will not be published. Required fields are marked *