43.21 Block System Sleep and Process Sleep Events

Function: system-sleep-block-sleep &optional why allow-display-sleep

This function blocks the system from entering its idle sleep state.

It returns a token that must be passed to system-sleep-unblock-sleep to unblock this specific block (other sleep blocks may be simultaneously in force for other purposes). Otherwise, it returns nil if the sleep blocking fails.

why is a string and, when non-nil, is used to identify the sleep block as it may appear on the system’s inspectable block lists. It defaults to ‘Emacs’.

If allow-display-sleep is non-nil, allow the display to sleep. By default, the display is kept active.

Note that when the Emacs process terminates, blocks are released on all platforms.

Function: system-sleep-unblock-sleep token

This function unblocks the sleep block associated with token. It returns non-nil on success, otherwise it returns nil.

Macro: with-system-sleep-block (&optional why allow-display-sleep) body…

This is a convenience macro that lets you wrap the forms in body with a sleep block that is unblocked for you when body completes. This guarantees that the system will never go to sleep while body executes. The arguments have the same meaning as in system-sleep-block-sleep, above.

Function: system-sleep-sleep-blocked-p

This predicate function returns non-nil if there are any active system-sleep blocks, otherwise it returns nil.

Function: system-sleep-unblock-all-sleep-blocks

This function unblocks all active sleep blocks. It is unlikely that you will need to call this function.

User Option: system-sleep-event-functions

When the system is about to enter a sleep state or after it wakes from one, each function on this abnormal hook is called with one argument, event, a sleep event. Its state can be retrieved via ‘(sleep-event-state event)’. State will be one of the symbols pre-sleep or post-wake.

Handling pre-sleep events should be done as fast as possible and avoid user prompting. Systems often grant a very short pre-sleep processing interval, typically ranging between 2 and 5 seconds. The system may sleep even if your processing is not complete, so be sure you do as little as possible. For example, your function could close active connections or serial ports.

Handling post-wake events offers more leeway. Use this, for example, to reestablish connections.

Note: Your code, or the functions it calls, should not raise any signals or all hooks will be halted. You can wrap your code in a condition-case block (see Errors).