我该如何确定计算机已经通电的时间(以毫秒为单位)?
我该如何确定计算机已经通电的时间(以毫秒为单位)?
net stats srv
命令,在Unix中,您可以执行uptime
命令。必须解析每个输出以获取正常运行时间。该方法通过检测用户的操作系统自动执行所需的命令。public static long getSystemUptime() throws Exception {
long uptime = -1;
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
Process uptimeProc = Runtime.getRuntime().exec("net stats srv");
BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
if (line.startsWith("Statistics since")) {
SimpleDateFormat format = new SimpleDateFormat("'Statistics since' MM/dd/yyyy hh:mm:ss a");
Date boottime = format.parse(line);
uptime = System.currentTimeMillis() - boottime.getTime();
break;
}
}
} else if (os.contains("mac") || os.contains("nix") || os.contains("nux") || os.contains("aix")) {
Process uptimeProc = Runtime.getRuntime().exec("uptime");
BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
String line = in.readLine();
if (line != null) {
Pattern parse = Pattern.compile("((\\d+) days,)? (\\d+):(\\d+)");
Matcher matcher = parse.matcher(line);
if (matcher.find()) {
String _days = matcher.group(2);
String _hours = matcher.group(3);
String _minutes = matcher.group(4);
int days = _days != null ? Integer.parseInt(_days) : 0;
int hours = _hours != null ? Integer.parseInt(_hours) : 0;
int minutes = _minutes != null ? Integer.parseInt(_minutes) : 0;
uptime = (minutes * 60000) + (hours * 60000 * 60) + (days * 6000 * 60 * 24);
}
}
}
return uptime;
}
new SystemInfo().getOperatingSystem().getSystemUptime()
System.out.println("Uptime: "+FormatUtil.formatElapsedSecs(new oshi.SystemInfo().getOperatingSystem().getSystemUptime()));
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.4.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.4.0</version>
</dependency>
对于Windows系统,您可以通过查询windows WMI
来获得毫秒级别的uptime
。
要运行以下代码,您需要下载Jawin库,并将jawin.dll
添加到您的eclipse项目根目录中。
public static void main(String[] args) throws COMException {
String computerName = "";
String userName = "";
String password = "";
String namespace = "root/cimv2";
String queryProcessor = "SELECT * FROM Win32_OperatingSystem";
DispatchPtr dispatcher = null;
try {
ISWbemLocator locator = new ISWbemLocator(
"WbemScripting.SWbemLocator");
ISWbemServices wbemServices = locator.ConnectServer(computerName,
namespace, userName, password, "", "", 0, dispatcher);
ISWbemObjectSet wbemObjectSet = wbemServices.ExecQuery(
queryProcessor, "WQL", 0, null);
DispatchPtr[] results = new DispatchPtr[wbemObjectSet.getCount()];
IUnknown unknown = wbemObjectSet.get_NewEnum();
IEnumVariant enumVariant = (IEnumVariant) unknown
.queryInterface(IEnumVariant.class);
enumVariant.Next(wbemObjectSet.getCount(), results);
for (int i = 0; i < results.length; i++) {
ISWbemObject wbemObject = (ISWbemObject) results[i]
.queryInterface(ISWbemObject.class);
System.out.println("Uptime: "
+ wbemObject.get("LastBootUpTime"));
}
} catch (COMException e) {
e.printStackTrace();
}
我实在想不出一种与操作系统无关的解决方案。
一个选项是使用ManagementFactory.getRuntimeMXBean().getUptime();
,它返回JVM的运行时间,虽然不完全符合你的需求,但已经是朝着正确方向迈出的一步。
你到底想用这些数据达到什么目的?
我希望找到一种不需要使用库的解决方案,使用WMIC是最适合我的。
private DateTime getSystemBootTime() throws IOException {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
Process uptimeProc = Runtime.getRuntime().exec("WMIC os get lastbootuptime");
BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
if (line.startsWith("ERROR")) {
logger.error("CheckMachineUptime failed. WMIC operation failed. MACHINE OS: {} CMD output: {}", os, line);
break;
}
if (line.startsWith("2")) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
try {
return new DateTime(format.parse(line));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
logger.error("Task failed! Could not identify time format. CMD OUTPUT: {}", in.readLine());
} else logger.error("Task failed! Could not identify machine OS. MACHINE OS: {}", os);
throw new RuntimeException("Getting uptime failed");
}