Is there a way to use systemd to start/stop services when a laptop is on battery or logged in?

As a developer it's helpful to have things like mongodb and redis autostart, but I would like to suspend them when on battery to save as much as possible.

  • The version of systemd in Ubuntu 15.04 has a condition named ConditionACPower that you can use to determine if a service should start. However, this condition is checked only when starting the service, so if the AC power is disconnected after the service is started, then the service will still continue. – saiarcot895 Jul 30 '15 at 18:46

I'm not an expert on systemd, but I google better than the average bear. See https://wiki.archlinux.org/index.php/Power_management:

There is just one thing systemd cannot do (as of systemd-204): power management depending on whether the system is running on AC or battery. To fill this gap, you can create a single udev rule that runs a script when the AC adapter is plugged and unplugged:

Further instructions follow.

My guess is you want to do something like create a fake service called acpluggedin.service which is started and stopped by the udev rule, and then have the mongo and redis services Requires it. Or something.

  • Thanks! I had found that page but missed that comment. It's a strange limitation (and people say that systemd does too much). Marking as accepted answer, and hoping in the future something better comes along. – Ivo Anjo Aug 3 '15 at 21:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.