user867662
user867662

Reputation: 1171

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?

Upvotes: 25

Views: 53373

Answers (5)

Pavan
Pavan

Reputation: 3425

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

Upvotes: 28

Preetam Sikdar
Preetam Sikdar

Reputation: 41

import java.io.*;
import java.util.*;

public class ServiceStartStop {
    public static void main(String args[]) {
        String[] command = {"cmd.exe", "/c", "net", "start", "Mobility Client"};
        try {
            Process process = new ProcessBuilder(command).start();
            InputStream inputStream = process.getInputStream(); 
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch(Exception ex) {
            System.out.println("Exception : "+ex);
        }
    }
}

It worked fine .... instead of "sc" use "net" command.

Upvotes: 4

Jayan
Jayan

Reputation: 18459

Did you try JNA? It has some good api to do this.

JNA is very active in SO - you could come back here with specific questions.

Upvotes: 0

Rocky
Rocky

Reputation: 951

You can execute system commands from java using the exec () command - A simple tutorial on the same can be found here - http://www.java-samples.com/showtutorial.php?tutorialid=8

Now you can use the system commands to start / stop windows services - A sample of the same can be found here

http://www.windowsitpro.com/article/registry2/how-can-i-stop-and-start-services-from-the-command-line-

I am not very sure about monitoring the status , so can't be of much help in that regards

Upvotes: 2

jatanp
jatanp

Reputation: 4092

You may execute following commands via Runtime#exec method.

net start and net stop (full information is available at : http://technet.microsoft.com/en-us/library/cc736564%28WS.10%29.aspx)

Probably you will have to use cmd /c net start as it would execute the command under shell.

Upvotes: 0

Related Questions