Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start windows service from java

Tags:

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?

like image 463
user867662 Avatar asked Jan 31 '12 05:01

user867662


2 Answers

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);
like image 111
pavan Avatar answered Oct 05 '22 09:10

pavan


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.

like image 33
Preetam Sikdar Avatar answered Oct 05 '22 09:10

Preetam Sikdar