<p>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.</p>

<p>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.</p>

<p>Any ideas?</p>

[{'answer_id': 52882, 'author': 'Gulzar Nazim', 'author_id': 4337, 'author_profile': 'https://Stackoverflow.com/users/4337', 'pm_score': 0, 'selected': False, 'text': '<p>Run a command inside a timer like pinging the server..</p>\n'}, {'answer_id': 52885, 'author': 'zigdon', 'author_id': 4913, 'author_profile': 'https://Stackoverflow.com/users/4913', 'pm_score': 1, 'selected': False, 'text': "<p>Wouldn't it be easier to disable the power management on the server?  It might be argued that servers shouldn't go into powersave mode?</p>\n"}, {'answer_id': 52888, 'author': 'Keng', 'author_id': 730, 'author_profile': 'https://Stackoverflow.com/users/730', 'pm_score': 3, 'selected': False, 'text': "<p>I have a very brute-force technique of moving the mouse 1 point in the x direction and then back every 3 minutes.</p>\n\n<p>There may me a more elegant solution but it's a quick fix.</p>\n"}, {'answer_id': 52906, 'author': 'Matt Dillard', 'author_id': 863, 'author_profile': 'https://Stackoverflow.com/users/863', 'pm_score': 4, 'selected': False, 'text': '<p>On Windows, use the <a href="http://msdn.microsoft.com/en-us/library/ms724947.aspx" rel="noreferrer">SystemParametersInfo</a> function.  It\'s a Swiss army-style function that lets you get/set all sorts of system settings.</p>\n\n<p>To disable the screen shutting off, for instance:</p>\n\n<pre><code>SystemParametersInfo( SPI_SETPOWEROFFACTIVE, 0, NULL, 0 );\n</code></pre>\n\n<p>Just be sure to set it back when you\'re done...</p>\n'}, {'answer_id': 52913, 'author': 'Paulj', 'author_id': 5433, 'author_profile': 'https://Stackoverflow.com/users/5433', 'pm_score': 0, 'selected': False, 'text': "<p>I'd just do a function (or download a freebie app) that moves the mouse around. Inelegant, but easy.</p>\n"}, {'answer_id': 52966, 'author': 'ScArcher2', 'author_id': 1310, 'author_profile': 'https://Stackoverflow.com/users/1310', 'pm_score': 6, 'selected': True, 'text': "<p>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.</p>\n\n<p>It's a hack, not an elegant solution.</p>\n\n<pre><code>import java.awt.*;\nimport java.util.*;\npublic class Hal{\n\n    public static void main(String[] args) throws Exception{\n        Robot hal = new Robot();\n        Random random = new Random();\n        while(true){\n            hal.delay(1000 * 60);\n            int x = random.nextInt() % 640;\n            int y = random.nextInt() % 480;\n            hal.mouseMove(x,y);\n        }\n    }\n}\n</code></pre>\n"}, {'answer_id': 53176, 'author': 'zigdon', 'author_id': 4913, 'author_profile': 'https://Stackoverflow.com/users/4913', 'pm_score': 3, 'selected': False, 'text': "<p>Wouldn't all the suggestions moving the mouse back and forth drive the user crazy?  I know I'd remove any app that would do that as soon as I can isolate it.</p>\n"}, {'answer_id': 53276, 'author': 'David Crow', 'author_id': 2783, 'author_profile': 'https://Stackoverflow.com/users/2783', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve been using <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/pmset.1.html" rel="nofollow noreferrer">pmset</a> to control sleep mode on my Mac for awhile now, and it\'s pretty easy to integrate. Here\'s a rough example of how you could call that program from Java to disable/enable sleep mode. Note that you need root privileges to run pmset, and therefore you\'ll need them to run this program.</p>\n\n<pre><code>import java.io.BufferedInputStream;\nimport java.io.IOException;\n\n/**\n * Disable sleep mode (record current setting beforehand), and re-enable sleep\n * mode. Works with Mac OS X using the "pmset" command.\n */\npublic class SleepSwitch {\n\n    private int sleepTime = -1;\n\n    public void disableSleep() throws IOException {\n        if (sleepTime != -1) {\n            // sleep time is already recorded, assume sleep is disabled\n            return;\n        }\n\n        // query pmset for the current setting\n        Process proc = Runtime.getRuntime().exec("pmset -g");\n        BufferedInputStream is = new BufferedInputStream(proc.getInputStream());\n        StringBuffer output = new StringBuffer();\n        int c;\n        while ((c = is.read()) != -1) {\n            output.append((char) c);\n        }\n        is.close();\n\n        // parse the current setting and store the sleep time\n        String outString = output.toString();\n        String setting = outString.substring(outString.indexOf(" sleep\\t")).trim();\n        setting = setting.substring(7, setting.indexOf(" ")).trim();\n        sleepTime = Integer.parseInt(setting);\n\n        // set the sleep time to zero (disable sleep)\n        Runtime.getRuntime().exec("pmset sleep 0");\n    }\n\n    public void enableSleep() throws IOException {\n        if (sleepTime == -1) {\n            // sleep time is not recorded, assume sleep is enabled\n            return;\n        }\n\n        // set the sleep time to the previously stored value\n        Runtime.getRuntime().exec("pmset sleep " + sleepTime);\n\n        // reset the stored sleep time\n        sleepTime = -1;\n    }\n}\n</code></pre>\n'}, {'answer_id': 93610, 'author': 'Milhous', 'author_id': 17712, 'author_profile': 'https://Stackoverflow.com/users/17712', 'pm_score': 2, 'selected': False, 'text': '<p>You can use the program Caffeine <a href="http://lightheadsw.com/caffeine/" rel="nofollow noreferrer">caffiene</a> to keep your workstation awake.  You could run the program via the open command in os X.</p>\n'}, {'answer_id': 10280104, 'author': 'asloob', 'author_id': 603125, 'author_profile': 'https://Stackoverflow.com/users/603125', 'pm_score': 3, 'selected': False, 'text': '<p>Adding to scarcher2\'s code snippet above and moving mouse by only 1 pixel. I have moved the mouse twice so that some change occurs even if pointer is on extremes:</p>\n\n<pre><code>while(true){\n            hal.delay(1000 * 30);       \n            Point pObj = MouseInfo.getPointerInfo().getLocation();\n            System.out.println(pObj.toString() + "x&gt;&gt;" + pObj.x + "  y&gt;&gt;" + pObj.y);\n            hal.mouseMove(pObj.x + 1, pObj.y + 1);  \n            hal.mouseMove(pObj.x - 1, pObj.y - 1);\n            pObj = MouseInfo.getPointerInfo().getLocation();\n            System.out.println(pObj.toString() + "x&gt;&gt;" + pObj.x + "  y&gt;&gt;" + pObj.y);\n        }\n</code></pre>\n'}, {'answer_id': 19349044, 'author': 'Javier Carmona', 'author_id': 2041804, 'author_profile': 'https://Stackoverflow.com/users/2041804', 'pm_score': 1, 'selected': False, 'text': "<p>This code moves the pointer to the same location where it already is so the user doesn't notice any difference.</p>\n\n<pre><code>while (true) {\n    Thread.sleep(180000);//this is how long before it moves\n    Point mouseLoc = MouseInfo.getPointerInfo().getLocation();\n    Robot rob = new Robot();\n    rob.mouseMove(mouseLoc.x, mouseLoc.y);\n}\n</code></pre>\n"}, {'answer_id': 30313322, 'author': 'ihatetoregister', 'author_id': 517748, 'author_profile': 'https://Stackoverflow.com/users/517748', 'pm_score': 2, 'selected': False, 'text': '<p>On OS X, just spawn <code>caffeinate</code>. This will prevent the system from sleeping until <code>caffeinate</code> is terminated.</p>\n'}, {'answer_id': 31192583, 'author': 'Felinis', 'author_id': 2941664, 'author_profile': 'https://Stackoverflow.com/users/2941664', 'pm_score': 2, 'selected': False, 'text': '<p>In Visual Studio create a simple form.\nFrom the toolbar, drag a Timer control onto the form.\nIn the Init code, set the timer interval to 60 seconds (60000 ms.).\nImplement the timer callback with the following code "SendKeys.Send("{F15}");"\nRun the new program.</p>\n\n<p>No mouse movement needed.</p>\n\n<p>Edit: At least on my Army workstation, simply programmatically generating mouse and key messages isn\'t enough to keep my workstation logged in and awake.  The early posters with the Java Robot class are on the right track.  JAVA Robot works on or below the OS\'s HAL (Hardware Abstraction Layer) However I recreated and tested the Java/Robot solution and it did not work - until I added a Robot.keyPress(123) to the code.</p>\n'}, {'answer_id': 50833568, 'author': 'Santosh Jadi', 'author_id': 3805521, 'author_profile': 'https://Stackoverflow.com/users/3805521', 'pm_score': 0, 'selected': False, 'text': '<p><strong>This will work:</strong></p>\n\n<pre><code>public class Utils {\n    public static void main(String[] args) throws AWTException {\n        Robot rob = new Robot();\n        PointerInfo ptr = null;\n        while (true) {\n            rob.delay(4000);  // Mouse moves every 4 seconds\n            ptr = MouseInfo.getPointerInfo();\n            rob.mouseMove((int) ptr.getLocation().getX() + 1, (int) ptr.getLocation().getY() + 1);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 54684339, 'author': 'Anand Varkey Philips', 'author_id': 3002336, 'author_profile': 'https://Stackoverflow.com/users/3002336', 'pm_score': 2, 'selected': False, 'text': '<p>Here is completed Batch file that generates java code, compile it, cleans the generated files, and runs in the background.. (jdk is required on your laptop)</p>\n<p><strong>Just save and run this as a Bat File. (somefilename.bat) ;)</strong></p>\n<pre><code>@echo off\nsetlocal\n\nrem rem if JAVA is set and run from :startapp labeled section below, else the program exit through :end labeled section.\nif not &quot;[%JAVA_HOME%]&quot;==&quot;[]&quot; goto start_app\necho. JAVA_HOME not set. Application will not run!\ngoto end\n\n\n:start_app\necho. Using java in %JAVA_HOME%\nrem writes below code to Energy.java file.\n@echo import java.awt.MouseInfo; &gt; Energy.java\n@echo import java.awt.Point; &gt;&gt; Energy.java\n@echo import java.awt.Robot; &gt;&gt; Energy.java\n@echo //Mouse Movement Simulation &gt;&gt; Energy.java\n@echo public class Energy { &gt;&gt; Energy.java\n@echo     public static void main(String[] args) throws Exception { &gt;&gt; Energy.java\n@echo         Robot energy = new Robot(); &gt;&gt; Energy.java\n@echo         while (true) { &gt;&gt; Energy.java\n@echo             energy.delay(1000 * 60); &gt;&gt; Energy.java\n@echo             Point pObj = MouseInfo.getPointerInfo().getLocation(); &gt;&gt; Energy.java\n@echo             Point pObj2 = pObj;  &gt;&gt; Energy.java\n@echo             System.out.println(pObj.toString() + &quot;x&gt;&gt;&quot; + pObj.x + &quot;  y&gt;&gt;&quot; + pObj.y); &gt;&gt; Energy.java\n@echo             energy.mouseMove(pObj.x + 10, pObj.y + 10); &gt;&gt; Energy.java\n@echo             energy.mouseMove(pObj.x - 10, pObj.y - 10); &gt;&gt; Energy.java\n@echo             energy.mouseMove(pObj2.x, pObj.y); &gt;&gt; Energy.java\n@echo             pObj = MouseInfo.getPointerInfo().getLocation(); &gt;&gt; Energy.java\n@echo             System.out.println(pObj.toString() + &quot;x&gt;&gt;&quot; + pObj.x + &quot;  y&gt;&gt;&quot; + pObj.y); &gt;&gt; Energy.java\n@echo         } &gt;&gt; Energy.java\n@echo     } &gt;&gt; Energy.java\n@echo } &gt;&gt; Energy.java\n\nrem compile java code.\njavac Energy.java\nrem run java application in background.\nstart javaw Energy\necho. Your Secret Energy program is running...\ngoto end\n\n:end\nrem clean if files are created.\npause\ndel &quot;Energy.class&quot;\ndel &quot;Energy.java&quot;\n</code></pre>\n'}, {'answer_id': 56146892, 'author': 'maris', 'author_id': 3853452, 'author_profile': 'https://Stackoverflow.com/users/3853452', 'pm_score': -1, 'selected': False, 'text': '<p>One simple way which i use to avoid "Windows desktop Auto lock" is "Switch On/Off NumLock" every 6 seconds.</p>\n\n<p>Here a Java Program to Switch ON/OFF NumLock.</p>\n\n<pre><code>import java.util.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class NumLock extends Thread {\n  public void run() {\n    try {\n    boolean flag = true;\n    do {\n        flag = !flag;\n\n        Thread.sleep(6000);\n        Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent. VK_NUM_LOCK, flag);\n    }\n    while(true);\n    }\n    catch(Exception e) {}\n  }\n\n  public static void main(String[] args) throws Exception {\n    new NumLock().start();\n  }\n}\n</code></pre>\n\n<p>Run this Java program in a separate command prompt; :-)</p>\n'}, {'answer_id': 65890299, 'author': 'Gili', 'author_id': 14731, 'author_profile': 'https://Stackoverflow.com/users/14731', 'pm_score': 3, 'selected': False, 'text': '<p>A much cleaner solution is use JNA to tap into the native OS API. Check your platform at runtime, and if it happens to be Windows then the following will work:</p>\n<pre><code>import com.sun.jna.Native;\nimport com.sun.jna.Structure;\nimport com.sun.jna.Structure.FieldOrder;\nimport com.sun.jna.platform.win32.WTypes.LPWSTR;\nimport com.sun.jna.platform.win32.WinBase;\nimport com.sun.jna.platform.win32.WinDef.DWORD;\nimport com.sun.jna.platform.win32.WinDef.ULONG;\nimport com.sun.jna.platform.win32.WinNT.HANDLE;\nimport com.sun.jna.win32.StdCallLibrary;\n\n/**\n * Power management.\n *\n * @see &lt;a href=&quot;https://stackoverflow.com/a/20996135/14731&quot;&gt;https://stackoverflow.com/a/20996135/14731&lt;/a&gt;\n */\npublic enum PowerManagement\n{\n    INSTANCE;\n\n    @FieldOrder({&quot;version&quot;, &quot;flags&quot;, &quot;simpleReasonString&quot;})\n    public static class REASON_CONTEXT extends Structure\n    {\n        public static class ByReference extends REASON_CONTEXT implements Structure.ByReference\n        {\n        }\n\n        public ULONG version;\n        public DWORD flags;\n        public LPWSTR simpleReasonString;\n    }\n\n    private interface Kernel32 extends StdCallLibrary\n    {\n        HANDLE PowerCreateRequest(REASON_CONTEXT.ByReference context);\n\n        /**\n         * @param powerRequestHandle the handle returned by {@link #PowerCreateRequest(REASON_CONTEXT.ByReference)}\n         * @param requestType        requestType is the ordinal value of {@link PowerRequestType}\n         * @return true on success\n         */\n        boolean PowerSetRequest(HANDLE powerRequestHandle, int requestType);\n\n        /**\n         * @param powerRequestHandle the handle returned by {@link #PowerCreateRequest(REASON_CONTEXT.ByReference)}\n         * @param requestType        requestType is the ordinal value of {@link PowerRequestType}\n         * @return true on success\n         */\n        boolean PowerClearRequest(HANDLE powerRequestHandle, int requestType);\n\n        enum PowerRequestType\n        {\n            PowerRequestDisplayRequired,\n            PowerRequestSystemRequired,\n            PowerRequestAwayModeRequired,\n            PowerRequestMaximum\n        }\n    }\n\n    private final Kernel32 kernel32;\n    private HANDLE handle = null;\n\n    PowerManagement()\n    {\n        // Found in winnt.h\n        ULONG POWER_REQUEST_CONTEXT_VERSION = new ULONG(0);\n        DWORD POWER_REQUEST_CONTEXT_SIMPLE_STRING = new DWORD(0x1);\n\n        kernel32 = Native.load(&quot;kernel32&quot;, Kernel32.class);\n        REASON_CONTEXT.ByReference context = new REASON_CONTEXT.ByReference();\n        context.version = POWER_REQUEST_CONTEXT_VERSION;\n        context.flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;\n        context.simpleReasonString = new LPWSTR(&quot;Your reason for changing the power setting&quot;);\n        handle = kernel32.PowerCreateRequest(context);\n        if (handle == WinBase.INVALID_HANDLE_VALUE)\n            throw new AssertionError(Native.getLastError());\n    }\n\n    /**\n     * Prevent the computer from going to sleep while the application is running.\n     */\n    public void preventSleep()\n    {\n        if (!kernel32.PowerSetRequest(handle, Kernel32.PowerRequestType.PowerRequestSystemRequired.ordinal()))\n            throw new AssertionError(&quot;PowerSetRequest() failed&quot;);\n    }\n\n    /**\n     * Allow the computer to go to sleep.\n     */\n    public void allowSleep()\n    {\n        if (!kernel32.PowerClearRequest(handle, Kernel32.PowerRequestType.PowerRequestSystemRequired.ordinal()))\n            throw new AssertionError(&quot;PowerClearRequest() failed&quot;);\n    }\n}\n</code></pre>\n<p>Then when the user runs <code>powercfg /requests</code> they see:</p>\n<pre><code>SYSTEM:\n[PROCESS] \\Device\\HarddiskVolume1\\Users\\Gili\\.jdks\\openjdk-15.0.2\\bin\\java.exe\nYour reason for changing the power setting\n</code></pre>\n<p>You should be able to do something similar for macOS and Linux.</p>\n'}, {'answer_id': 67442227, 'author': 'Douglas Patriarche', 'author_id': 92137, 'author_profile': 'https://Stackoverflow.com/users/92137', 'pm_score': 2, 'selected': False, 'text': "<p>To go with the solution provided by user Gili for Windows using JNA, here's the JNA solution for MacOS.</p>\n<p>First, the JNA library interface:</p>\n<pre><code>import com.sun.jna.Library;\nimport com.sun.jna.Native;\nimport com.sun.jna.platform.mac.CoreFoundation;\nimport com.sun.jna.ptr.IntByReference;\n\npublic interface ExampleIOKit extends Library {\n    ExampleIOKit INSTANCE = Native.load(&quot;IOKit&quot;, ExampleIOKit.class);\n\n    CoreFoundation.CFStringRef kIOPMAssertPreventUserIdleSystemSleep = CoreFoundation.CFStringRef.createCFString(&quot;PreventUserIdleSystemSleep&quot;);\n    CoreFoundation.CFStringRef kIOPMAssertPreventUserIdleDisplaySleep = CoreFoundation.CFStringRef.createCFString(&quot;PreventUserIdleDisplaySleep&quot;);\n\n    int kIOReturnSuccess = 0;\n\n    int kIOPMAssertionLevelOff = 0;\n    int kIOPMAssertionLevelOn = 255;\n\n    int IOPMAssertionCreateWithName(CoreFoundation.CFStringRef assertionType,\n                                    int assertionLevel,\n                                    CoreFoundation.CFStringRef reasonForActivity,\n                                    IntByReference assertionId);\n\n    int IOPMAssertionRelease(int assertionId);\n}\n</code></pre>\n<p>Here's an example of invoking the JNA method to turn sleep prevention on or off:</p>\n<pre><code>public class Example {\n    private static final Logger _log = LoggerFactory.getLogger(Example.class);\n\n    private int sleepPreventionAssertionId = 0;\n\n    public void updateSleepPrevention(final boolean isEnabled) {\n        if (isEnabled) {\n            if (sleepPreventionAssertionId == 0) {\n                final var assertionIdRef = new IntByReference(0);\n                final var reason = CoreFoundation.CFStringRef.createCFString(\n                    &quot;Example preventing display sleep&quot;);\n                final int result = ExampleIOKit.INSTANCE.IOPMAssertionCreateWithName(\n                    ExampleIOKit.kIOPMAssertPreventUserIdleDisplaySleep,\n                    ExampleIOKit.kIOPMAssertionLevelOn, reason, assertionIdRef);\n                if (result == ExampleIOKit.kIOReturnSuccess) {\n                    _log.info(&quot;Display sleep prevention enabled&quot;);\n                    sleepPreventionAssertionId = assertionIdRef.getValue();\n                }\n                else {\n                    _log.error(&quot;IOPMAssertionCreateWithName returned {}&quot;, result);\n                }\n            }\n        }\n        else {\n            if (sleepPreventionAssertionId != 0) {\n                final int result = ExampleIOKit.INSTANCE.IOPMAssertionRelease(sleepPreventionAssertionId);\n                if (result == ExampleIOKit.kIOReturnSuccess) {\n                    _log.info(&quot;Display sleep prevention disabled&quot;);\n                }\n                else {\n                    _log.error(&quot;IOPMAssertionRelease returned {}&quot;, result);\n                }\n                sleepPreventionAssertionId = 0;\n            }\n        }\n    }\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/52874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338/']