javawindows-services

Start Windows service from Java


How can we start/stop a Windows Service from Java? For example, I would like to start and stop the mysql Windows Service from Java.

If start/stop is possible, then is it possible to know whether the service is started successfully or not?


Solution

  • You can formulate a Command Prompt script to start, stop, and check status on a service using a String Array:

    // start service
    String[] script = {"cmd.exe", "/c", "sc", "start", SERVICE_NAME};
    
    // stop service
    String[] script = {"cmd.exe", "/c", "sc", "stop", SERVICE_NAME};
    
    // check whether service is running or not
    String[] script = {"cmd.exe", "/c", "sc", "query", APP_SERVICE_NAME, "|", "find", "/C", "\"RUNNING\""};
    

    Execute scripts using the following:

    Process process = Runtime.getRuntime().exec(script);