Is it possible in Java to detect when the computer goes into sleep mode? I've already tried to count seconds with Thread.sleep(1000)
but it seems as if it would continue counting in sleep mode.
Asked
Active
Viewed 240 times
0

eli2003
- 400
- 5
- 13
-
Can you clarify, "... but it seems as if it would continue counting in sleep mode"? Did you do a test and determine this? Or is this just a guess? If you did a test, can you provide the Java code and the steps you took to put your test machine to sleep? – erickson Sep 24 '19 at 15:16
-
Also, do you want to be signaled as the computer is going to sleep? Or to be able to detect a sleep upon awakening? – erickson Sep 24 '19 at 15:17
-
1https://stackoverflow.com/questions/1213127/detect-os-sleep-and-wake-up-events-in-java – Joop Eggen Sep 24 '19 at 15:18
-
Using Thread.sleep(1000) you will notice your seconds count start to lag over an extended period. Instead you should use java.util.Timer – ControlAltDel Sep 24 '19 at 15:21
-
@erickson i've written a program to track the running time of a device by adding one second every second. But if I turn my device into sleep mode, and wake it up 20s later, it doesn't continue where I put it into sleep mode – eli2003 Sep 24 '19 at 15:39
-
1@eli2003 If you want to know how much time has passed, including time spent sleeping, simply subtract the start time from the current time (i.e., `System.currentTImeMillis() - start`). If you want to skip time spent sleeping, then setting a recurring timer that increments a counter (sounds like what you have implemented) is the right approach: it will not be incremented while asleep. You can use both approaches to detect a discrepancy that indicates a sleep has occurred. – erickson Sep 24 '19 at 15:44