Toggle services in battery mode

Is there a way to toggle services or configuration when the laptop switches to battery mode? For example I’d like to turn off virtualisation services and other background services when in battery mode as I’ll probably just be browsing the web or something much less intensive.

Maybe somebody already wrote a hook that calls nixos-rebuild switch when the power cable is plugged/unplugged (and it’s debounced)? Or there’s a pkgs.lib.hardware.isBatteryOn? I wouldn’t mind calling nixos-rebuild switch manually too.

I don’t know how far you can extend it but there is TLP which is often used to modify settings for laptops on battery.
I use it for example to disable/enable Wifi:

Besides that, to me it wouldn’t make sense to call nixos-rebuild just to stop a service.
I would try to extend/modify the services so that they only run when connected to power.

It probably could just be a simple script which gets executed when you disconnect the notebook from power and it then stops the services.

You absolutely do not want run nixos-rebuild switch whenever this happens.

You will however have an issue if you use udev to trigger a service to run as it will not be able to connect to the systemd user instance for any user services.

I suggest instead deciding on a global path such as /run/on-battery or similar and then use path units (one for system services and one per user) and then use that to trigger a script that stops/kills whatever you want.

For the services you can set ConditionACPower= to avoid starting them if not plugged in. You’d still need something like TLP or a dbus hook to stop them if they are already running when you unplug power.

I knew that option already existed, when I found the above article!
I used it in one of my configs so that the hourly backups only run when connected to power.