Get the uptime of your Java VM
You don’t need JConsole or similar for just displaying the approximate uptime of your application respectively your Java Virtual Machine:
import java.lang.management.ManagementFactory; public class Demo { public static void main(String... args) { final long uptime = ManagementFactory.getRuntimeMXBean().getUptime(); System.out.println(String.format("Up for %dms", uptime)); } } |
If you use Joda-Time (and you should if you have anything to do with date/datetime processing), you can format it nicely like so:
import java.lang.management.ManagementFactory; import java.text.MessageFormat; import org.joda.time.Period; import org.joda.time.PeriodType; import org.joda.time.format.PeriodFormatter; import org.joda.time.format.PeriodFormatterBuilder; public class Demo { public static void main(String... args) { final Period vmUptime = new Period(ManagementFactory.getRuntimeMXBean().getUptime()).normalizedStandard(PeriodType.yearDayTime()); final PeriodFormatter pf = new PeriodFormatterBuilder() .printZeroAlways() .appendDays().appendLiteral(MessageFormat.format("{0,choice,0# days, |1# day, |2# days, }", vmUptime.getDays())) .minimumPrintedDigits(2) .appendHours().appendLiteral(":").appendMinutes() .toFormatter(); System.out.println(String.format("Up for %s", pf.print(vmUptime))); } } |
You also have a nice example of the often unknown MessageFormat.