How to call a function when waking from sleep or hibernation in Java?

I have a thread running in the background that calculates the time to a new day, waits for that time, and then refreshes its UI. How do I force the program to restart this thread when the computer wakes up from sleep or hibernation?

+3


source to share


1 answer


You have to configure your system to start Java application automatically on system startup. The question is how to respond to system hibernation.

This is not exactly what you asked, but I think it does the same thing: in a Java application, shorten your sleep duration (e.g. 5 minutes) and before you call Thread.sleep () calculate what time you think the stream should wake up. If the current time when you wake up is significantly different from what you expected, you can assume that system hibernation exists and you can adjust any time estimates for the new day. Of course, if you sleep at n-minute intervals, you can simply set your logic to sleep for n minutes or until midnight, whichever comes first.



I ran this code on a VM that I could pause and it was correctly identified when the VM was paused:

    long pause = 10000L;
    long error = 100L;

    while (true) {
        long sleepTil = System.currentTimeMillis() + pause + error;
        try { Thread.sleep(pause); } catch (InterruptedException e) { }
        if (System.currentTimeMillis() > sleepTil) {
            System.out.println("System was suspended");
        } else {
            System.out.println("System was not suspended.");
        }       
    }

      

+3


source







All Articles