Skip to content
This repository has been archived by the owner on Feb 16, 2021. It is now read-only.

Chronometer

Phil Gaiser edited this page Sep 30, 2018 · 1 revision

Chronometer

As the name suggests, Chronometer is a simple class for measuring time. It makes code more readable by not having to make calls to System.currentTimeMillis() and then doing all the calculations. A simple example would be:

Chronometer chrono = new Chronometer().start();
doMagic();
chrono.stop();

The above code will construct a new Chronometer instance, start it, do some magic and, when doMagic() returns, stop time measurement. This effectively measures the runtime of the doMagic() method. You may then call one of the elapsed*() methods to get the total time elapsed in the desired unit. Alternatively, since Chronometer overrides the toString() method, you can print the time as a formatted string:

System.out.println(chrono);

NOTE: You don't necessarily have to stop your Chronometer instance in order to measure time.

Setting up a Timer

A Chronometer can also notify you after a predefined amount of time has elapsed. In order for this to happen, you must call setTimer() and pass it a callback. For example:

Chronometer chrono = new Chronometer();
chrono.setTimer(Duration.ofSeconds(30), new Timer(){
	@Override
	public void onTick(long elapsed){
		System.out.println(chrono);
	}
});
chrono.start();

This will call onTick() every 30 seconds and print out the elapsed time until you call stop(). Are more concise version of this using lambda expressions would be:

Chronometer chrono = new Chronometer();
chrono.setTimer(Duration.ofSeconds(30), (elapsed) -> {System.out.println(chrono);}).start();

If you want to get notified only once then you should call stop() after the first call to onTick(). For example, the following code will execute doMagic() only once, in 5 minutes in the future:

Chronometer chrono = new Chronometer();
chrono.setTimer(Duration.ofMinutes(5), (elapsed) -> {
	chrono.stop(); 
	doMagic();
}).start();
Clone this wiki locally