Question

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?

Was it helpful?

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

OTHER TIPS

I've heard stories of people getting a large sub-woofer, then duct taping a box lid to the top. You can then put the mouse in the box and turn up the music. Preferably something with a lot of bass that will keep the mouse moving around.

On Windows, use the SystemParametersInfo function. It's a Swiss army-style function that lets you get/set all sorts of system settings.

To disable the screen shutting off, for instance:

SystemParametersInfo( SPI_SETPOWEROFFACTIVE, 0, NULL, 0 );

Just be sure to set it back when you're done...

I have a very brute-force technique of moving the mouse 1 point in the x direction and then back every 3 minutes.

There may me a more elegant solution but it's a quick fix.

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:

while(true){
            hal.delay(1000 * 30);       
            Point pObj = MouseInfo.getPointerInfo().getLocation();
            System.out.println(pObj.toString() + "x>>" + pObj.x + "  y>>" + pObj.y);
            hal.mouseMove(pObj.x + 1, pObj.y + 1);  
            hal.mouseMove(pObj.x - 1, pObj.y - 1);
            pObj = MouseInfo.getPointerInfo().getLocation();
            System.out.println(pObj.toString() + "x>>" + pObj.x + "  y>>" + pObj.y);
        }

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.

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?

I've been using pmset 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.

import java.io.BufferedInputStream;
import java.io.IOException;

/**
 * Disable sleep mode (record current setting beforehand), and re-enable sleep
 * mode. Works with Mac OS X using the "pmset" command.
 */
public class SleepSwitch {

    private int sleepTime = -1;

    public void disableSleep() throws IOException {
        if (sleepTime != -1) {
            // sleep time is already recorded, assume sleep is disabled
            return;
        }

        // query pmset for the current setting
        Process proc = Runtime.getRuntime().exec("pmset -g");
        BufferedInputStream is = new BufferedInputStream(proc.getInputStream());
        StringBuffer output = new StringBuffer();
        int c;
        while ((c = is.read()) != -1) {
            output.append((char) c);
        }
        is.close();

        // parse the current setting and store the sleep time
        String outString = output.toString();
        String setting = outString.substring(outString.indexOf(" sleep\t")).trim();
        setting = setting.substring(7, setting.indexOf(" ")).trim();
        sleepTime = Integer.parseInt(setting);

        // set the sleep time to zero (disable sleep)
        Runtime.getRuntime().exec("pmset sleep 0");
    }

    public void enableSleep() throws IOException {
        if (sleepTime == -1) {
            // sleep time is not recorded, assume sleep is enabled
            return;
        }

        // set the sleep time to the previously stored value
        Runtime.getRuntime().exec("pmset sleep " + sleepTime);

        // reset the stored sleep time
        sleepTime = -1;
    }
}

You can use the program Caffeine caffiene to keep your workstation awake. You could run the program via the open command in os X.

In Visual Studio create a simple form. From the toolbar, drag a Timer control onto the form. In the Init code, set the timer interval to 60 seconds (60000 ms.). Implement the timer callback with the following code "SendKeys.Send("{F15}");" Run the new program.

No mouse movement needed.

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.

Run a command inside a timer like pinging the server..

I'd just do a function (or download a freebie app) that moves the mouse around. Inelegant, but easy.

This code moves the pointer to the same location where it already is so the user doesn't notice any difference.

while (true) {
    Thread.sleep(180000);//this is how long before it moves
    Point mouseLoc = MouseInfo.getPointerInfo().getLocation();
    Robot rob = new Robot();
    rob.mouseMove(mouseLoc.x, mouseLoc.y);
}

On OS X, just spawn caffeinate. This will prevent the system from sleeping until caffeinate is terminated.

This will work:

public class Utils {
    public static void main(String[] args) throws AWTException {
        Robot rob = new Robot();
        PointerInfo ptr = null;
        while (true) {
            rob.delay(4000);  // Mouse moves every 4 seconds
            ptr = MouseInfo.getPointerInfo();
            rob.mouseMove((int) ptr.getLocation().getX() + 1, (int) ptr.getLocation().getY() + 1);
        }
    }
}

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)

Just run this Bat File ;)

@echo off
setlocal

rem rem if JAVA is set and run from :startapp labeled section below, else the program exit through :end labeled section.
if not "[%JAVA_HOME%]"=="[]" goto start_app
echo. JAVA_HOME not set. Application will not run!
goto end


:start_app
echo. Using java in %JAVA_HOME%
rem writes below code to Energy.java file.
@echo import java.awt.MouseInfo; > Energy.java
@echo import java.awt.Point; >> Energy.java
@echo import java.awt.Robot; >> Energy.java
@echo //Mouse Movement Simulation >> Energy.java
@echo public class Energy { >> Energy.java
@echo     public static void main(String[] args) throws Exception { >> Energy.java
@echo         Robot energy = new Robot(); >> Energy.java
@echo         while (true) { >> Energy.java
@echo             energy.delay(1000 * 60); >> Energy.java
@echo             Point pObj = MouseInfo.getPointerInfo().getLocation(); >> Energy.java
@echo             Point pObj2 = pObj;  >> Energy.java
@echo             System.out.println(pObj.toString() + "x>>" + pObj.x + "  y>>" + pObj.y); >> Energy.java
@echo             energy.mouseMove(pObj.x + 10, pObj.y + 10); >> Energy.java
@echo             energy.mouseMove(pObj.x - 10, pObj.y - 10); >> Energy.java
@echo             energy.mouseMove(pObj2.x, pObj.y); >> Energy.java
@echo             pObj = MouseInfo.getPointerInfo().getLocation(); >> Energy.java
@echo             System.out.println(pObj.toString() + "x>>" + pObj.x + "  y>>" + pObj.y); >> Energy.java
@echo         } >> Energy.java
@echo     } >> Energy.java
@echo } >> Energy.java

rem compile java code.
javac Energy.java
rem run java application in background.
start javaw Energy
echo. Your Secret Energy program is running...
goto end

:end
rem clean if files are created.
pause
del "Energy.class"
del "Energy.java"

One simple way which i use to avoid "Windows desktop Auto lock" is "Switch On/Off NumLock" every 6 seconds.

Here a Java Program to Switch ON/OFF NumLock.

import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class NumLock extends Thread {
  public void run() {
    try {
    boolean flag = true;
    do {
        flag = !flag;

        Thread.sleep(6000);
        Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent. VK_NUM_LOCK, flag);
    }
    while(true);
    }
    catch(Exception e) {}
  }

  public static void main(String[] args) throws Exception {
    new NumLock().start();
  }
}

Run this Java program in a separate command prompt; :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top