Linux low power automatic shutdown method
- 2020-12-13 19:15:30
- OfStack
preface
Recently, the electricity in my apartment is not stable, and I often lose power suddenly. Although I have a laptop, it is not certain that I can receive the power, so it won't be long before the SSD in my laptop will be in a dead rhythm.
So I wrote a simple script, when the power is low, it will shut down, and then cooperate with crontab or systemd timers to check regularly.
About crontab command usage you can reference here: https: / / www ofstack. com article / 148575. htm
Without further ado, let's take a look at the details
check_shutdown.timer:
$ cat /etc/systemd/system/check_shutdown.timer
[Unit]
Description=Check if battery is low every 10 minutes
[Timer]
OnCalendar=*:0/10
Persistent=true
[Install]
WantedBy=timers.target
check_shutdown.service:
$ cat /etc/systemd/system/check_shutdown.service
[Service]
ExecStart=
ExecStart=/home/jiajun/.xmonad/scripts/shutdown.py
check_shutdown.py:
#!/home/jiajun/.py3k/bin/python
import psutil
import logging
import os
import datetime
bat = psutil.sensors_battery()
logging.warn("%s: battery status: %s", datetime.datetime.now(), bat)
if bat.percent < 15:
logging.warn("gonna shutdown")
os.system("sudo shutdown -h now")
conclusion