gpt4 book ai didi

java - 在 Java 中等待 Windows 服务启动/停止?

转载 作者:可可西里 更新时间:2023-11-01 11:18:32 27 4
gpt4 key购买 nike

我正在寻找一种方法来循环检查 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) {
}

请帮忙,谢谢!

最佳答案

我已经使用了您的代码,并且它正在我的窗口机器上运行。请重试。

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

关于java - 在 Java 中等待 Windows 服务启动/停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24972947/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com