Ubuntu – Prevent sleep if CPU usage is high

suspend

Is there a simple way to prevent the PC from going to sleep if there is high CPU activity? I need to run long processes overnight, so I want the PC to stay up while my processes are running, without any user activity, but when the processing is finished, the PC should go to sleep after the sleep timeout.

A solution with a "resetSleepTimer" function that I can call from my code (python ideally) would also be acceptable.


A clarification following comments from WinEunuuchs2Unix and Joaquín Ayuso de Paúl: unfortunately your solution works only if there is a single process, but I have normally more than one process running, with variable duration, so if one process ends and re-enables a short sleep timeout, it will sc*@w over the others still running. With resetSleepTimer function, I mean something to be called at regular intervals to reset the suspend timer. My previous (deleted) suggestion of simulating a user input wouldn't work, because it would also keep the screen ON.


Edit: a requirement as mentioned in a comment by OP:

Will this leave the screen on the whole time? Not what I'm looking for. Also, will acting on the screensaver also affect the sleep/suspend timeout?

Best Answer

Based of from this thread, you can disable the sleep process through the duration of your program by calling to idle inhibition via DBus:

org.freedesktop.ScreenSaver.Inhibit

Or you can ping it periodically:

org.freedesktop.ScreenSaver.SimulateUserActivity

If you need to prevent the computer to sleep at all, you can disable temporally (again through dBus) the behavior and then reinstate it. This will kick the screensaver but won't let the computer sleep:

  $ sudo -u gdm dbus-launch gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-ac-type 'nothing'
Related Question