So you've got an ubuntu box you want on during business hours, but you don't need it on outside business hours. Maybe it's a build server or something similar. Obviously, you could manually start it every morning - but you might be ill or go on holiday. Let's automate it with wake-on-RTC! The instructions below are for Ubuntu 14.04.

First of all, create this file at /root/ (I use sudo pico /root/ but you can use any text editor you like!)

set -e # Exit on failure

# For some reason, if wakealarm is already set it's an error to set it
# to a new value - unless we first clear it by writing 0 to it.
echo 0 > /sys/class/rtc/rtc0/wakealarm

# 1=Monday, 7=Sunday
current_day_of_week=$( date '+%u' )

if [ "$current_day_of_week" -lt "5" ]; then

# This bit determines the time of day for the next boot:
next_boot_text=$( date '+%Y-%m-%dT08:50:00' -d "+$sleep_for_days days" )
next_boot_unix=$( date '+%s' --date="$next_boot_text" )

echo "$next_boot_unix" > /sys/class/rtc/rtc0/wakealarm
cat /sys/class/rtc/rtc0/wakealarm
echo "Scheduled wake for $next_boot_text = $next_boot_unix"

# You can make a call to cronitor or here if you like.

Then make it executable and edit root's crontab:

chmod u+x /root/
sudo crontab -e

And add the following lines:

# m  h      dom  mon  dow   command
0    10,17  *    *    *     /root/ > /root/last-restart.log 2>&1
0    20     *    *    *     pm-suspend

Scheduling the restart will log the results (and any errors) to /root/last-restart.log so if you have any trouble you can debug it easily.

The pm-suspend line suspends the box at 20:00 but the wake-on-rtc will work just as well if you power off the box entirely. This can also give you a convenient chance to apply any updates - but if you're going to run apt-get, make sure your script sets the path so it works right under cron.


16 June 2016

Tags · Home · Archive · Tags