logo
Jiff Slater
🤔 About
✍️ Contact
📚Knowledge
25 Feb 2021
 

Scheduling a shutdown with systemd
16 January 2021

Occasionally, you’ll make a change in Linux that might be a bit precarious – you commit the change with a hesitation anticipation of a problem or uncertainty on the next reboot. In these cases, it may be desirable to schedule a shutdown if nothing is done within a certain time period.

I do this frequently when I’m testing changes to a Raspberry Pi that doesn’t have an off button. This reduces the likelihood that I need to turn off the device by removing power (a problematic shut-off method that can cause problems with the SD card).

If systemd is available, you can create a new timer that executes after a set amount of time.

We’ll create a systemd unit that executes after the multi-user target has completed.

Create a small script to trigger the auto-reboot.

/usr/local/bin/auto-poweroff.sh
#!/bin/bash
/usr/bin/sleep 60
/sbin/poweroff

/etc/systemd/system/auto-poweroff.service
[Unit]
Description="Automatically power off after a period of time."
Type=oneshot
IgnoreOnIsolate=yes
After=ssh.service

[Service]
ExecStart=/usr/local/bin/auto-poweroff.sh

[Install]
WantedBy=multi-user.target

Finally create the symlink into the multi-user.target directory.

cd /etc/systemd/system/multi-user.target.wants/
ln -s ../auto-poweroff.sh