Class: Timers

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/timers.rb,
lib/timers/version.rb

Overview

Low precision timers implemented in pure Ruby

Defined Under Namespace

Classes: Timer

Constant Summary collapse

VERSION =
"1.1.0"

Instance Method Summary collapse

Constructor Details

#initializeTimers

Returns a new instance of Timers.


11
12
13
# File 'lib/timers.rb', line 11

def initialize
  @timers = SortedSet.new
end

Instance Method Details

#add(timer) ⇒ Object

Raises:

  • (TypeError)

59
60
61
62
# File 'lib/timers.rb', line 59

def add(timer)
  raise TypeError, "not a Timers::Timer" unless timer.is_a? Timers::Timer
  @timers.add(timer)
end

#after(interval, &block) ⇒ Object

Call the given block after the given interval


16
17
18
# File 'lib/timers.rb', line 16

def after(interval, &block)
  Timer.new(self, interval, false, &block)
end

#after_milliseconds(interval, &block) ⇒ Object Also known as: after_ms

Call the given block after the given interval has expired. interval is measured in milliseconds.

Timer.new.after_milliseconds(25) { puts "fired!" }

25
26
27
# File 'lib/timers.rb', line 25

def after_milliseconds(interval, &block)
  after(interval / 1000.0, &block)
end

#every(interval, &block) ⇒ Object

Call the given block periodically at the given interval


31
32
33
# File 'lib/timers.rb', line 31

def every(interval, &block)
  Timer.new(self, interval, true, &block)
end

#fire(now = Time.now) ⇒ Object

Fire all timers that are ready


51
52
53
54
55
56
57
# File 'lib/timers.rb', line 51

def fire(now = Time.now)
  time = now + 0.001 # Fudge 1ms in case of clock imprecision
  while (timer = @timers.first) && (time >= timer.time)
    @timers.delete timer
    timer.fire(now)
  end
end

#waitObject

Wait for the next timer and fire it


36
37
38
39
40
# File 'lib/timers.rb', line 36

def wait
  i = wait_interval
  sleep i if i
  fire
end

#wait_interval(now = Time.now) ⇒ Object

Interval to wait until when the next timer will fire


43
44
45
46
47
48
# File 'lib/timers.rb', line 43

def wait_interval(now = Time.now)
  timer = @timers.first
  return unless timer
  interval = timer.time - now
  interval > 0 ? interval : 0
end