简体   繁体   中英

How to trigger function on waking up from sleep or hibernate in Java?

I have thread working in background that calculates time before new day, waits for that time and then updates my UI. How to make program restart this thread when computer wakes up from sleep or hibernate?

You ought to be able to configure your system to auto-start your Java app when the system starts up. The question is how to react to the system hibernating.

It's not quite what you asked for, but I think this does the same thing: Within the Java app, make your sleep durations shorter (eg 5 minutes) and before you call Thread.sleep() calculate what time you think the thread should wake up. If the current time when you wake up is significantly different than what you expected, you can assume there was a system hibernate and you can adjust any time-to-new-day estimates. Of course, if you're sleeping at n-minute intervals, then you might just adjust your logic to sleep for n minutes or until midnight, whichever is sooner.

I ran this code on a virtual machine that I could suspend and it correctly identified when the VM was suspended:

    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.");
        }       
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM