23

I've written an application in java and I want to add a feature to report the uptime of the application. Is there a Class/method in the JVM that can do this?

Should I save the timestamp when application starts, then calculate the difference with the current uptime in the moment of the request?

What's a better way to retrieve application uptime in Java?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
aleroot
  • 71,077
  • 30
  • 176
  • 213

4 Answers4

47

You can use RuntimeMXBean.getUptime()

RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
long uptime = rb.getUptime();
Honza Zidek
  • 9,204
  • 4
  • 72
  • 118
Rob Harrop
  • 3,445
  • 26
  • 26
  • It is retuens JVM uptime not an application. – Kamahire Jun 21 '11 at 20:40
  • 3
    That's not necessarily different. In the Java EE context, they might be different things, but for standalone applications, runtime uptime and application uptime are one in the same. – Rob Harrop Jun 21 '11 at 20:42
  • and the jvm is the place where your application runs. – Asad Rasheed Jun 21 '11 at 20:42
  • What's the difference? As far as application servers/servlet containers aren't taken into account? Based on the question we can assume the OP wants to how much time did it elapsed since the application startup, not the uptime percentage. – Tomasz Nurkiewicz Jun 21 '11 at 20:43
1

The result is in milliseconds:

RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();
System.out.println(mxBean.getUptime());

See: ManagementFactory.getRuntimeMXBean() javadoc.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
-1

It is just like Heartbeat application. IN which You have write small application which communicate to your java application. Whenever You application start you have to store the time with date in file/database. Monitor application will check the application running or not. The monitor application also take difference of end time and start time sand display the application time.

Kamahire
  • 2,149
  • 3
  • 21
  • 50
-6

The solution I know is to use System.currentTimeMillis() as it's described here and here. There also was similar question

Community
  • 1
  • 1
nikagra
  • 835
  • 2
  • 9
  • 23
  • That's not what he's looking for. He is looking for application uptime (how long has the application been running). Your solution will give the current time. – Jean-Marc S. Feb 17 '16 at 05:22
  • 1
    If you check links provided, you'll find that `currentTimeMillis` can be used to measure application uptime, i.e. by subtracting start time from current time in millis. So if we are speaking about my solution, it will not give current time – nikagra Feb 17 '16 at 14:15