linuxcronpower-managementcrontrigger

How to set cronjob on wake up from sleep?


For example if you want a cron job to run after each reboot, you add something like this to your cron file:

@reboot ./do_sth

Is there something similar to that for waking up from a sleep state?


Solution

  • This is not something that can be managed by cron, but it can be managed by the Power Management Utilities (pm-utils). When reading man pm-action, you find:

    /etc/pm/sleep.d, /usr/lib/pm-utils/sleep.d: Programs in these directories (called hooks) are combined and executed in C sort order before suspend and hibernate with as argument suspend or hibernate. Afterwards, they are called in reverse order with argument resume and thaw respectively. If both directories contain a similar named file, the one in /etc/pm/sleep.d will get preference. It is possible to disable a hook in the distribution directory by putting a non-executable file in /etc/pm/sleep.d, or by adding it to the HOOK_BLACKLIST configuration variable.

    So all you need to do is create a script in /etc/pm/sleep.d that looks like this:

    #!/usr/bin/env bash
    action="$1"
    
    case "$action" in
       suspend)
            # List programs to run before, the system suspends
            # to ram; some folks call this "sleep"
       ;;
       resume)
            # List of programs to when the systems "resumes"
            # after being suspended
       ;;
       hibernate)
            # List of programs to run before the system hibernates
            # to disk; includes power-off, looks like shutdown
       ;;
       thaw)
            # List of programs to run when the system wakes
            # up from hibernation
       ;;
    esac
    

    Obviously, you can alter this if you do not want to distinguish between suspend and hibernate, or resume and thaw into something like:

    #!/usr/bin/env bash
    action="$1"
    case "$action" in
       suspend|hibernate) stuff ;;
       resume|thaw)       stuff ;;
    esac