class Timer

Ruby license. Copyright (C)2004-2009 Joel VanderWerf. Contact vjoel@users.sourceforge.net.

A lightweight, non-drifting, self-correcting timer. Average error is bounded as long as, on average, there is enough time to complete the work done, and the timer is checked often enough. It is lightweight in the sense that no threads are created. Can be used either as an internal iterator (Timer.every) or as an external iterator (Timer.new). Obviously, the GC can cause a temporary slippage.

Simple usage:

require 'timer'

Timer.every(0.1, 0.5) { |elapsed| puts elapsed }

timer = Timer.new(0.1)
5.times do
  puts timer.elapsed
  timer.wait
end

Attributes

period[RW]

Public Class Methods

every(period, expire = nil) { |elapsed| ... } click to toggle source

Yields to the supplied block every period seconds. The value yielded is the total elapsed time (an instance of Time). If expire is given, then every returns after that amount of elapsed time.

   # File lib/tkar/timer.rb
27 def Timer.every(period, expire = nil)
28   target = time_start = Time.now
29   loop do
30     elapsed = Time.now - time_start
31     break if expire and elapsed > expire
32     yield elapsed
33     target += period
34     error = target - Time.now
35     sleep error if error > 0
36   end
37 end
new(period = 1) click to toggle source

Make a Timer that can be checked when needed, using wait or if_ready. The advantage over Timer.every is that the timer can be checked on separate passes through a loop.

   # File lib/tkar/timer.rb
42 def initialize(period = 1)
43   @period = period
44   restart
45 end

Public Instance Methods

elapsed() click to toggle source

Time on timer since instantiation or last restart.

   # File lib/tkar/timer.rb
56 def elapsed
57   Time.now - @time_start
58 end
if_ready() { |elapsed| ... } click to toggle source

Yield to the block if no time remains in cycle. Otherwise, return immediately to caller

   # File lib/tkar/timer.rb
71 def if_ready
72   error = @target + @period - Time.now
73   if error <= 0
74     @target += @period
75     elapsed = Time.now - @time_start
76     yield elapsed
77   end
78 end
restart() click to toggle source

Call this to restart the timer after a period of inactivity (e.g., the user hits the pause button, and then hits the go button).

   # File lib/tkar/timer.rb
51 def restart
52   @target = @time_start = Time.now
53 end
wait(per = nil) click to toggle source

Wait for the next cycle, if time remains in the current cycle. Otherwise, return immediately to caller.

   # File lib/tkar/timer.rb
62 def wait(per = nil)
63   @target += per || @period
64   error = @target - Time.now
65   sleep error if error > 0
66   true
67 end