I wanted to create a stopwatch program in ruby so I googled it and found this SO Q.
But over there, the author calls the tick
function with 1000xxx.times
. I wanted to know how I can do it using something like (every second).times
or for each increment of second do call the tick
function.
This function:
When used like this:
Results in this:
The trick is to sleep for less than a second. That helps to keep you from losing ticks. Note that you cannot guarantee you'll never lose a tick. That's because the operating system cannot guarantee that your unprivileged program gets processor time when it wants it.
Therefore, make sure your clock code does not depend on the block getting called every second. For example, this would be bad:
This would be fine: