views:

82

answers:

3

I'd like a timer class that allows me to call:

.start()   .getElapsedTime()   .stop()   .reset()

Does Java have such a class, or do I need to use my own (which I've already written).

From a best-practice point of view, I should use the Java class libraries classes if they exist, but I'm not sure whether this one does.

Can anyone give me a link to the javadoc for this class, if it exists?

+1  A: 

Java has a Timer class, but I suppose that you are looking for a StopWatch or a Chronometer. There are many implementations of these available in the net.

kgiannakakis
[this](http://commons.apache.org/lang/api-release/org/apache/commons/lang/time/StopWatch.html#getTime(\)) looks close to what I want.
Eric
+2  A: 

There's a StopWatch class in Apache Commons Lang.

To start the watch, call start(). At this point you can:

  • split() the watch to get the time whilst the watch continues in the background. unsplit() will remove the effect of the split. At this point, these three options are available again.
  • suspend() the watch to pause it. resume() allows the watch to continue. Any time between the suspend and resume will not be counted in the total. At this point, these three options are available again.
  • stop() the watch to complete the timing session.

It is intended that the output methods toString() and getTime() should only be called after stop, split or suspend, however a suitable result will be returned at other points.

API links


On using libraries

Yes, most definitely you should try to use good libraries whenever you can, instead of reinventing the wheel. The value of a well-designed, well-written, well-tested library is insurmountable, and Java has lots of it. The more users it acquires, the more mature it becomes, and any kinks would usually get fixed quickly.

Related questions

polygenelubricants
A: 

About java.util.Timer.scheduleAtFixedRate(), be aware of this bug: http://bugs.sun.com/view_bug.do?bug_id=4290274

ungarida
-1 for having no connection whatsoever with the question asked.
Kevin Bourrillion
I know it was not stricly conneted but it was a warning. I worked with a platform based on java.util.Timer and there were big problems for this bug... a lot of money loss. Anyway I accept the -1
ungarida