Search code examples
javawindowsmacoscross-platformoperating-system

How do you keep the machine awake?


I have a piece of server-ish software written in Java to run on Windows and OS X. (It is not running on a server, but just a normal user's PC - something like a torrent client.) I would like the software to signal to the OS to keep the machine awake (prevent it from going into sleep mode) while it is active.

Of course I don't expect there to be a cross platform solution, but I would love to have some very minimal C programs/scripts that my app can spawn to inform the OS to stay awake.

Any ideas?


Solution

  • I use this code to keep my workstation from locking. It's currently only set to move the mouse once every minute, you could easily adjust it though.

    It's a hack, not an elegant solution.

    import java.awt.*;
    import java.util.*;
    public class Hal{
    
        public static void main(String[] args) throws Exception{
            Robot hal = new Robot();
            Random random = new Random();
            while(true){
                hal.delay(1000 * 60);
                int x = random.nextInt() % 640;
                int y = random.nextInt() % 480;
                hal.mouseMove(x,y);
            }
        }
    }