我正在寻找一种方法来继续检查循环中Windows服务的状态,直到它完全弯腰或启动。
我使用Malik Ehtasham代码Here来获取服务的状态。但我必须按下按钮才能获得状态。我想它只是继续检查状态说...请等待..然后说弯腰或开始。
这就是我必须启动服务的原因:
String[] StartSpooler = {"cmd.exe", "/c", "sc", "start", "spooler"};
try {
Process process = new ProcessBuilder(StartSpooler).start();
InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String StartSpoolerLine;
while ((StartSpoolerLine= bufferedReader.readLine()) != null) {
System.out.println(StartSpoolerLine);
}
} catch (Exception ex) {
System.out.println("Exception : " + ex);
}
这是我必须继续检查服务状态但它无法正常工作
try {
Process p = Runtime.getRuntime().exec("sc query spooler");
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
if (line.trim().startsWith("STATE")) {
while (!"4".equals(line.trim().substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim())) {
System.out.println("Starting....");
}
System.out.println("Service is started and running");
}
line = reader.readLine();
}
} catch (IOException e1) {
}
请帮助,谢谢!
答案 0 :(得分:2)
我已经使用了你的代码,这正在我的窗口机器上工作..请再试一次。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class WindowServiceTest {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("sc query spooler");
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
if (line.trim().startsWith("STATE")) {
while (!"4".equals(line.trim().substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim())) {
System.out.println("Starting....");
}
System.out.println("... Service is started and running");
}
line = reader.readLine();
System.out.println("SERVICE DETAILS --> "+ line);
}
} catch (IOException e1) {
}
}
}
OUTPUT
===========
SERVICE DETAILS --> SERVICE_NAME: spooler
SERVICE DETAILS --> TYPE : 110 WIN32_OWN_PROCESS (interactive)
SERVICE DETAILS --> STATE : 4 RUNNING
... Service is started and running
SERVICE DETAILS --> (STOPPABLE,NOT_PAUSABLE,ACCEPTS_SHUTDOWN)
SERVICE DETAILS --> WIN32_EXIT_CODE : 0 (0x0)
SERVICE DETAILS --> SERVICE_EXIT_CODE : 0 (0x0)
SERVICE DETAILS --> CHECKPOINT : 0x0
SERVICE DETAILS --> WAIT_HINT : 0x0
SERVICE DETAILS --> null
答案 1 :(得分:2)
这对我很有用。
private static String[] scriptStart = { "net", "start", SERVICE_NAME};
private static String[] scriptStop = {"net", "stop", SERVICE_NAME};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(scriptStart);//or scriptStop
process.waitFor();