Ubuntu: Suspend and reboot at specific times using Cron

Harry Lee

February 8, 2015

If you have a server at home and you want it to be on only during specific times and not 247, this script is for you.

Cron not only is the best tool for this, it also handles scheduled tasks.

Cron is a system daemon used to execute desired tasks (in the background) at designated times.

Method

  1. Install Cron on Ubuntu if it is not already installed.

  2. Create a new file, suspend_until, in your ~/Documents/ and place the following contents in it. This script is written by Romke van der Meulen.

    #!/bin/bash
    
    # Auto suspend and wake-up script
    #
    # Puts the computer on standby and automatically wakes it up at specified time
    #
    # Written by Romke van der Meulen <redge.online@gmail.com>
    # Minor mods fossfreedom for AskUbuntu
    #
    # Takes a 24hour time HH:MM as its argument
    # Example:
    # suspend_until 9:30
    # suspend_until 18:45
    
    # ------------------------------------------------------
    # Argument check
    if [ $# -lt 1 ]; then
    echo "Usage: suspend_until HH:MM"
    exit
    fi
    
    # Check whether specified time today or tomorrow
    DESIRED=$((`date +%s -d "$1"`))
    NOW=$((`date +%s`))
    if [ $DESIRED -lt $NOW ]; then
    DESIRED=$((`date +%s -d "$1"` + 24*60*60))
    fi
    
    # Kill rtcwake if already running
    sudo killall rtcwake
    
    # Set RTC wakeup time
    # N.B. change "mem" for the suspend option
    # find this by "man rtcwake"
    sudo rtcwake -a -m disk -t $DESIRED &
    
    # feedback
    echo "Suspending..."
    
    # give rtcwake some time to make its stuff
    sleep 2
    
    # then suspend
    # N.B. dont usually require this bit
    #sudo pm-suspend
    
    # Any commands you want to launch after wakeup can be placed here
    # Remember: sudo may have expired by now
    
    # Wake up with monitor enabled N.B. change "on" for "off" if
    # you want the monitor to be disabled on wake
    xset dpms force on
    
    # and a fresh console
    clear
    echo "Good morning!"
    
    
  3. Change the permission of the file so that it is executable.

         $ sudo chmod +x ~/Documents/suspend_until
    
  4. Run crontab.

         $ sudo crontab -e
    
  5. Place the following line at the end of the file.

          00 02 * * * /home/user/Documents/suspend_until 09:00
    

    This basically tells the server to execute the suspend_until script at 2:00 AM. The 09:00 appended at the end of the line tells the server to wake up at 9:00 AM. The details are all explained in the script.

  6. Save the crontab file and reboot.