How do I configure Ubuntu to reboot every day at a given time?
Solution 1:
Edit the crontab entries using crontab -e
command (by default this will edit the current logged-in users crontab) and add the following line:
0 3 * * * echo $PASSWD | sudo -S reboot
#change $PASSWD with your password
Save the file and check the new crontab entry with crontab -l
.
If you want to use only:
0 3 * * * sudo reboot
as crontab, this doesn't work normally and you should check this post to see how can you make it to work.
Or, simple add the crontab to the root user's crontab file offering the complete path for the reboot
command using sudo crontab -e
:
0 3 * * * /sbin/reboot
Solution 2:
Note that putting your clear-text password in a text file is not a good idea, so it's best to have this job run as root from the get-go. Usually, rather than editing root's crontab via the crontab
command, which leaves the entries in /var/spool/cron/crontabs
, a somewhat cryptic location, I prefer to enter them explicitly in /etc/cron.d
. Entries in cron.d are run as system crontab entries, are treated as config files so they should survive system reboots, updates and upgrades, and you can explicitly specify the running user:
echo "0 3 * * * root /sbin/shutdown -h 5 'System will reboot in 5 minutes'" | sudo tee /etc/cron.d/reboot-at-3-am
If you don't need a specific time, but rather, just want the system to reboot once daily, add an executable or script in /etc/cron.daily
and it will be automatically run at a predetermined time (6:25 AM system time by default):
echo "/sbin/shutdown -h 5 'System will reboot in 5 minutes'" | sudo tee /etc/cron.daily/reboot-me
Notice that rather than just rebooting the system without warning, I'm setting a 5-minute warning, so if anyone is logged in, they have a chance to save their work, or even interrupt the shutdown with sudo shutdown -c
, rather than having the system pulled off from under them. You can adjust these accordingly, if you want to give more ample warning (for instance, use shutdown -h 60
and run the command at 2:00 AM and you'll give users a generous 1-hour warning).
This is based on my past experience; at some point you will be logged in working when the crontab entry runs, and if it just reboots without warning you'll be a very sad panda.