This article describes how you can use RTC (Real-time Clock) alarm to setup your Linux box to automatically shutdown and start up at a given time each day.
I have a Linux server which runs as a file network system so that I can access my files and media on a central repository. I used to have the server running 24/7 but seeing that I’m usually not home during the day, it would be more energy efficient to have it run at certain times of the day (when I am home).
It’s pretty easy to shutdown a machine at a given time, we use the shutdown command and add it to cron, the difficulty is with starting the machine back up again. There’s always the option of using a hardware power timer and have your BIOS setup to boot up when there is power, but in this article we’ll look at using the RTC (real-time clock) alarm to startup your computer.
For my setup, I like to have the computer shutdown at 1am every weekday and boot up again at 6pm. Sometimes I am on the computer to late, so 1am would be late enough that I won’t have the situation of the server shutting down on me when I am still working on it. And I normally don’t get back on the computer till after dinner, so having the server start up at 6pm will ensure that the server is running when I use it. And I don’t shutdown and startup the server on weekdays as my computer usage on weekend vary so its easier to just let the server run through the weekend.
From 1am to 6pm, that’s 17 hours where the computer will be powered off, so I started by creating a bash shell script.
echo 0 > /sys/class/rtc/rtc0/wakealarm
echo `date ‘+%s’ -d ‘+ 17 hours’` > /sys/class/rtc/rtc0/wakealarm
shutdown -h now
Saved the code to somewhere common e.g: /opt/scripts/configureRtcAlarmAndShutdown.sh
And chmod the file to make it executable. $chmod a+x /opt/scripts/configureRtcAlarmAndShutdown.sh
Next modify the cron job to execute the script at 1am on weekdays. (Put it in root’s cron entry)
Add the following entry
0 1 * * [1-6] /opt/scripts/configureRtcAlarmAndShutdown.sh
Save the cron job and you’re done!
Its best to test it out first to see if the script is working correctly and that your computer can do RTC alarms. Do the test by setting an early wake time (e.g: 5 minutes) and by executing the script manually. Remember to execute the script as root. I remembered when I was testing it that sudo doesn’t work, you need to change to root user.
There you go, now you have a more energy efficient server. Having the server running only 7hrs instead of 24hrs and also as it only runs in the evening, during the summer you avoid the heat of the day and the server’s fans wouldn’t be running as hard.
Hope this article has been useful for you. It has been something which I had wanted for a long time and only recently found out how to do it.