Skip to content

Instantly share code, notes, and snippets.

Last active December 7, 2023 22:18
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Suspend and then hibernate after 60 minutes

I found a post about suspending and then going into hibernate that included a really clever script. Turns out that with NixOS this is even esaier to coordinate as you have systemd so can have a before and after service. I just include this in my /etc/nixos/configuration.nix file and nixos-rebuild; then a systemctl suspend or a close of the lid will cause the hibernate timer to be set.

{ config, pkgs, ... }: let
hibernateEnvironment = {
HIBERNATE_LOCK = "/var/run/autohibernate.lock";
in {"awake-after-suspend-for-a-time" = {
description = "Sets up the suspend so that it'll wake for hibernation";
wantedBy = [ "" ];
before = [ "systemd-suspend.service" ];
environment = hibernateEnvironment;
script = ''
curtime=$(date +%s)
echo "$curtime $1" >> /tmp/autohibernate.log
echo "$curtime" > $HIBERNATE_LOCK
${pkgs.utillinux}/bin/rtcwake -m no -s $HIBERNATE_SECONDS
serviceConfig.Type = "simple";
};"hibernate-after-recovery" = {
description = "Hibernates after a suspend recovery due to timeout";
wantedBy = [ "" ];
after = [ "systemd-suspend.service" ];
environment = hibernateEnvironment;
script = ''
curtime=$(date +%s)
sustime=$(cat $HIBERNATE_LOCK)
if [ $(($curtime - $sustime)) -ge $HIBERNATE_SECONDS ] ; then
systemctl hibernate
${pkgs.utillinux}/bin/rtcwake -m no -s 1
serviceConfig.Type = "simple";
Copy link

aou commented Apr 17, 2023

this is awesome! suspend-then-hibernate from systemd was first broken by a weird spat between the maintainer and everyone else, then kinda stopped working entirely for me. This config works, with one minor addition you might want to add at some point -- if you have an nvidia card and use the power management systemd services, then hibernate-after-recovery should come after "nvidia-resume.service".

Copy link

I tested it on my nixos setup and works as intended. Many thanks 😁. Was curious as to why before it goes to hibernation it needs to wake up first from suspend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment