java监控 程序是否启动
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class ProcessMonitor {
private static final String PROCESS_NAME = "ShakeMouse.exe";
private static final String APP_PATH = "C:\\Users\\ex_yaochengwei\\Desktop\\ShakeMouse.exe";
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
while (true) {
System.out.println("\n[ " + LocalDateTime.now().format(formatter) + " ] 监控进程 " + PROCESS_NAME + "...");
try {
Process taskListProcess = Runtime.getRuntime().exec("tasklist /NH /FI \"IMAGENAME eq " + PROCESS_NAME + "\"");
BufferedReader reader = new BufferedReader(new InputStreamReader(taskListProcess.getInputStream()));
String line;
boolean processFound = false;
while ((line = reader.readLine()) != null) {
if (line.contains(PROCESS_NAME)) {
processFound = true;
break;
}
}
reader.close();
if (!processFound) {
System.out.println("[ " + LocalDateTime.now().format(formatter) + " ] 进程未找到,尝试启动...");
Runtime.getRuntime().exec("\"" + APP_PATH + "\"");
System.out.println("[ " + LocalDateTime.now().format(formatter) + " ] 进程已启动.");
} else {
System.out.println("[ " + LocalDateTime.now().format(formatter) + " ] 进程正在运行.");
}
} catch (Exception e) {
System.err.println("发生错误: " + e.getMessage());
}
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}