Get system health in Java

How do you know how long (in milliseconds) your computer has been on?

+4


source to share


5 answers


On Windows, you can execute a command net stats srv

, and on Unix, you can execute a command uptime

. Each output must be analyzed to obtain uptime. This method automatically executes the required command, detecting the user's operating system.

Note that none of the operations return millisecond precision 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;
}

      

+9


source


Use the OSHI library that works on Windows, Linux and Mac OS.



new SystemInfo().getOperatingSystem().getSystemUptime()

      

+4


source


I can't think of an OS dependent way to do this. An option would be to use ManagementFactory.getRuntimeMXBean().getUptime();

Which returns the JVM runtime, so not exactly what you are looking for, but already a step in the right direction.

What exactly are you trying to accomplish with the data?

+2


source


For windows, you can get uptime

up to millisecond precision by askingwindows WMI

To run the below code you need to download the Jawin library and add jawin.dll

to your eclipse project root

 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();
    }

      

+2


source


You can use the OSHI library . here is a sample code

System.out.println("Uptime: "+FormatUtil.formatElapsedSecs(new oshi.SystemInfo().getOperatingSystem().getSystemUptime()));

      

For it to work, you 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>

      

+2


source







All Articles