Automatically shutting down an MPD server on inactivityPublished: 2014-03-22
Nowadays all modern Linux GUIs have powersaving options that allow you, like Windows, to set timeouts for inactivity. Even 'dumb' electronics like TVs, AVRs etc. have such functionality. However, for headless Linux setups, this seems to be a problem. You can e.g. set a timeout for pm-suspend, but this squarely ignores any tasks the system might be handling; suspend will happen no matter what. The same for the shutdown utilities: you can set timeouts, but that's it. It's just a timer. This is miles from what the GUI counterparts allow you to do.
My Zotac AD10 doubles as a HTPC (with OpenELEC) and an MPD server (on Debian Jessie). The only thing the headless Debian setup does is run MPD, maintenance being done over SSH and MPD being controlled through the excellent MPDroid Android application. So for me, it's pretty simple: if MPD isn't doing anything, there's really no reason for the box to be on.
After a bit of online research didn't turn up anything concerning existing frameworks, I decided to write a small Bash script of my own. You can download it here. It does the following:
- Periodically check for MPD activity. I have set it to 30 minutes but it's configurable;
- Log to syslog if there's no action to be taken, so you know the script is functional;
- Shut down after MPD has been inactive for 30 minutes or more. The action can be reconfigured as well (e.g. to suspend/hibernate instead).
It contains a testing sequence as well for quick debugging, I have kept it as simple as possible. Keep in mind your MPD log setting should be set to default, otherwise you will have to modify the check sequence. Now it just parses the last log entry. Add it to cron like this:
$ sudo crontab -l|grep mpdcheck */10 * * * * /usr/local/bin/mpdcheck
This will make cron run the script every ten minutes. You can run it less frequently, keep in mind though that the interval between latest MPD activity and actual shutdown will increase. If e.g. MPD stops playing at 14:01, and you set cron to run every half hour, it will be less than 30 minutes at the next check at 14:30, and only shut down at 15:00 (ie almost an hour after the last song played). You should see messages like this in your syslog every 10 minutes if everything's set up correctly:
Mar 22 13:32:15 elysium logger: Less than 30 minutes since last MPD activity. Not shutting down.