4

Context

I am developing a service for macOS that runs in the background and periodically performs certain tasks. The service is restarted automatically by launchd whenever it crashes or when it is automatically updated.

I have noticed that when the machine is asleep it will still execute programs during 1 or 2 minutes per hour.

Objective

My objective is to interrupt the execution of those tasks whenever the host is in the sleep state. For that I am processing the sleep and wake up notifications the system sends the application(Apple Docs: Registering and unregistering for sleep and wake notifications).

Problem

The problem I have found is that if the service is updated or it restarts while the system is in the sleep state, the service starts and assumes the state is "awake". Thus it tries to run things it shouldn't.

I am wondering if there is a way to query the system if it is in the "sleep" or "awake" state.

Santiago Alessandri
  • 6,630
  • 30
  • 46

1 Answers1

1

You can run system_profiler SPDisplaysDataType and parse the output to extract the Display Asleep state.

If nothing is found, the system is awake.

Graphics/Displays:

  NVIDIA GeForce GT 750M:

    Chipset Model: NVIDIA GeForce GT 750M
    Type: GPU
    Bus: PCIe
    PCIe Lane Width: x8
    VRAM (Total): 2 GB
    Vendor: NVIDIA (0x10de)
    Device ID: 0x0fe9
    Revision ID: 0x00a2
    ROM Revision: 3776
    Automatic Graphics Switching: Supported
    gMux Version: 4.0.8 [3.2.8]
    Metal Family: Supported, Metal GPUFamily macOS 1
    Displays:
      Color LCD:
        Display Type: Built-In Retina LCD
        Resolution: 2880 x 1800 Retina
        Framebuffer Depth: 24-Bit Color (ARGB8888)
        Mirror: Off
        Online: Yes
        Display Asleep: Yes
        Automatically Adjust Brightness: Yes
        Connection Type: Internal
Franc Jerez
  • 113
  • 3
  • 5
  • This is nice, just tried it. But is this just telling you that the _display_ is sleeping, not the whole mac? – Kubuntuer82 Mar 18 '21 at 10:34
  • 1
    Oddly enough, even if you turn off every external monitor and close the laptop lid, the `Display Sleep` state doesn't seem to get detected (not unless the OS is suspended/locked too). – Franc Jerez Mar 19 '21 at 12:48