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.
2 Answers
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.
-
Thanks, like the other comment said, this does seem like an XY problem, didn't know there was a better tool for the job. I'm reading the man page on systemd-inhibit right now. Apr 1, 2021 at 20:07
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
systemd
can run a script before and after suspend. You don't need cron for this. However, this looks like a XY problem. Does your ephemeral user log out or someone else log in? Or the same user is logged in while the person leaves and the desktop goes to sleep while idle? What will happen if the next user starts using the desktop before it suspends? Please add more details to your question.