How do I detect computer suspension using python?
Question:
I’m making an alarm using python, and I’m using time.sleep() to wait for alarm time. But if I suspend my computer, the sleep will suspend too, causing the alarm to sound after what was intended if I turn the computer on again.
I need a way for the program to detect when the computer is going to be suspended, and if not possible, to detect it has been suspended, so I can implement the timer correctly.
How can this be done with python?
Answers:
It is very easily to detect if it was likely suspended:
before = datetime.now()
sleep(1)
after = datetime.now()
if (after - before).total_seconds() > X:
# suspended
after - before
will never be exactly 1 second, but they should not be significantly larger than 1 second. You can play around to find best X.
If you are using Windows, you can do it like this:
import win32com.client
colMonitoredEvents = win32com.client.Dispatch("WbemScripting.SWbemLocator").ConnectServer(".", "rootcimv2").ExecNotificationQuery("Select * from Win32_PowerManagementEvent")
while True:
objLatestEvent = colMonitoredEvents.NextEvent()
if objLatestEvent.EventType == 4:
pass #do your stuff here
Event based, run it indefinitely with low CPU usage and do stuff when the event ID is 4. Note that the action should be very quick or likely it will not complete before entering sleep.
Event 7 is used instead when resuming from sleep.
I’m making an alarm using python, and I’m using time.sleep() to wait for alarm time. But if I suspend my computer, the sleep will suspend too, causing the alarm to sound after what was intended if I turn the computer on again.
I need a way for the program to detect when the computer is going to be suspended, and if not possible, to detect it has been suspended, so I can implement the timer correctly.
How can this be done with python?
It is very easily to detect if it was likely suspended:
before = datetime.now()
sleep(1)
after = datetime.now()
if (after - before).total_seconds() > X:
# suspended
after - before
will never be exactly 1 second, but they should not be significantly larger than 1 second. You can play around to find best X.
If you are using Windows, you can do it like this:
import win32com.client
colMonitoredEvents = win32com.client.Dispatch("WbemScripting.SWbemLocator").ConnectServer(".", "rootcimv2").ExecNotificationQuery("Select * from Win32_PowerManagementEvent")
while True:
objLatestEvent = colMonitoredEvents.NextEvent()
if objLatestEvent.EventType == 4:
pass #do your stuff here
Event based, run it indefinitely with low CPU usage and do stuff when the event ID is 4. Note that the action should be very quick or likely it will not complete before entering sleep.
Event 7 is used instead when resuming from sleep.