This answer is based on askubuntu.com/a/661747/394818 (as also referred to in the comment by @sun-bear), askubuntu.com/q/616272/394818 and superuser.com/a/1269158/585953.
Using a system service:
Create the file /etc/systemd/system/my_user_script.service
:
[Unit]
Description=Run my_user_script
After=suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target
[Service]
ExecStart=/path/to/my_user_script
#User=my_user_name
#Environment=DISPLAY=:0
[Install]
WantedBy=suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target
Remove suspend/hibernate/hybrid in case the service should only be executed after waking up from a specific type of sleep. In case the service needs to be run by a specific user, uncomment the User=
and Environment=
lines and replace the relevant user name.
Install the service file with:
sudo systemctl enable my_user_script
Using a user service will not work:
In order to avoid setting a hard coded user name with User=
, one could create the exact same service file at ~/.config/systemd/user/my_user_script.service
and activate with
systemctl --user enable my_user_script
However, that will not work. @grawity explains in more detail at unix.stackexchange.com/a/174837/163108 why that is:
sleep.target
is specific to system services. The reason is, sleep.target
is not a magic target that automatically gets activated when going to sleep. It's just a regular target that puts the system to sleep – so the 'user' instances of course won't have an equivalent. (And unfortunately the 'user' instances currently have no way to depend on systemwide services.)
If you need to script this, you should look into using the systemctl show
command. It is more useful for scripts than trying to parse anything from status
. For example, to find when the service last started you can use:
$ systemctl show systemd-journald --property=ActiveEnterTimestamp
ActiveEnterTimestamp=Wed 2017-11-08 05:55:17 UTC
If you would like to see all the properties available just omit the flag and it will dump them all out.
$ systemctl show <service_name>
The documentation for these properties can be found here.
Best Answer
You have two options:
You can set
TimeoutStopSpec=
on a specific UNIT to a specific value (in seconds*) to wait. You can also set it toinfinity
in which case SIGKILL will never be sent (not recommended as you may end up with runaway services that are hard to debug).Set
DefaultTimeoutStopSec=
inside/etc/systemd/system.conf
(oruser.conf
, or in one of the*.d
directories) to a default value that all UNITs that do not haveTimeoutStopSpec=
specified will use. The deafult for this setting is the 90s you normally see.Man page references:
man systemd.service
forTimeoutStopSpec=
man systemd-system.conf
forDefaultTimeoutStopSec=
* systemd also accepts time specs, e.g. "2min 3s". That's extensively described in the man.