在Windows中,我试图编写一个java程序来停止mysql服务并更新my.ini文件,然后启动mysql服务 . 它可以成功运作 . 我可以检查mysql服务的状态,即使用java代码启动/停止的状态 . 如果发生任何不可预测的情况,指定的服务无法启动/停止,也可以循环 . 请检查我的代码:
public void processStatusOfMySQLService() {
String[] commandScript = { "cmd.exe", "/c", "sc", "query", "MySQL" };
String STATE_PREFIX = "STATE : ";
Process process;
try {
process = new ProcessBuilder(commandScript).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
// check that the temp string contains the status prefix
int indexStatus = line.indexOf(STATE_PREFIX);
if (indexStatus >= 0) {
// compare status number to one of the states
String stateStr = line.substring(
indexStatus + STATE_PREFIX.length(),
indexStatus + STATE_PREFIX.length() + 1);
int state = Integer.parseInt(stateStr);
switch (state) {
case (1):
// service stopped
break;
case (4):
// service started
break;
case (2):
case (3):
// service pending
try {
Thread.sleep(1000);
processStatusOfMySQLService();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
br.close();
isr.close();
is.close();
process.destroy();
}
如果服务无法启动/停止,我需要在特定时间后退出循环 . 如何设置合适的超时值???