1

I want to run a cron job to wipe files for a ephemeral user on Ubuntu desktop 20.04. Since the system won't be powering fully off regularly(for which I could just use @reboot /path/to/my_script.sh ), is there a way to schedulae a cron job to run when the computer is suspended? Everything on Google I'm seeing is related to running cron jobs while the computer is suspended, but I'd like to use suspend, or waking as the trigger for this cron job.

user68186
  • 37,461

2 Answers2

3

That kind of trigger is not what cron is designed for. Cron is a clock-based trigger. @reboot is a convenience added to cron.

For suspend/remove jobs, one solution is to use power management.

  • See man pm-suspend
  • Put your job in the /etc/pm/sleep.d/ directory.
  • It's not a cron job. You place complete scripts in the directory.

Use case to determine what occurs on sleep, and what occurs on resume:

case "${1}" in
   suspend)
      suspend_actions
      ;;
   resume)
      resume_actions
      ;;
esac

Another similar solution is to use systemd.

  • The main difference is to use /lib/systemd/system-sleep/ instead of /etc/pm/sleep.d/

Both of these methods can arguably be considered a bit hacky: Don't use them for real applications, nor for long delays to suspending. Use inhibit instead.

user535733
  • 68,493
3

Alternate answer using systemd

Create a file /lib/systemd/system-sleep/my_script.sh with the following content:

#!/bin/bash
case $1/$2 in
    pre/*)
    # commands to be executed before suspend, hibernate, etc. goes below
    echo "This example does nothing"
    ;;
    post/*)
    # commands to be executed on wake, resume, etc. goes below
    echo "Nothing to see here"
    ;;
esac

Edit and add the commands you need to add instead of the lines starting with echo above. Save the file and make it executable. See How to make a file (e.g. a .sh script) executable, so it can be run from a terminal for more.

Hope this helps

user68186
  • 37,461