在 Java 中获取系统正常运行时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14800597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get system uptime in Java
提问by emillio5
How can I determine how long (in milliseconds) a computer has been powered on?
如何确定计算机已开启多长时间(以毫秒为单位)?
回答by FThompson
In Windows, you can execute the net stats srv
command, and in Unix, you can execute the uptime
command. Each output must be parsed to acquire the uptime. This method automatically executes the necessary command by detecting the user's operating system.
在 Windows 中可以执行net stats srv
命令,在 Unix 中可以执行uptime
命令。必须解析每个输出以获取正常运行时间。该方法通过检测用户的操作系统自动执行必要的命令。
Note that neither operation returns uptime in millisecond precision.
请注意,这两个操作都不会以毫秒精度返回正常运行时间。
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;
}
回答by Stefan Reich
Use the OSHI librarywhich works on Windows, Linux and Mac OS.
使用适用于 Windows、Linux 和 Mac OS的OSHI 库。
new SystemInfo().getOperatingSystem().getSystemUptime()
回答by Joshan George
You can use the OSHIlibrary. here is the sample code
您可以使用OSHI库。这是示例代码
System.out.println("Uptime: "+FormatUtil.formatElapsedSecs(new oshi.SystemInfo().getOperatingSystem().getSystemUptime()));
For getting it work need to add the following dependencies.
为了让它工作需要添加以下依赖项。
<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>
回答by Simon Verhoeven
I can't really think of a non OS dependant way to do this.
An option would be to use ManagementFactory.getRuntimeMXBean().getUptime();
Which returns your JVM uptime so not exactly what you're looking for but already a step in the right direction.
我真的想不出一种非操作系统依赖的方法来做到这一点。一个选择是使用ManagementFactory.getRuntimeMXBean().getUptime();
它返回您的 JVM 正常运行时间,所以这不是您正在寻找的,但已经朝着正确的方向迈出了一步。
What exactly are you trying to accomplish with the data?
你到底想用数据完成什么?
回答by iTech
For windows you can get uptime
to milliseconds accuracy by querying windows WMI
对于 Windows,您可以uptime
通过查询达到毫秒精度windows WMI
To run the below code, you will need to download Jawinlibrary and add jawin.dll
to your eclipse project root
要运行以下代码,您需要下载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();
}