Class: Celluloid::Timers

Inherits:
Object
  • Object
show all
Defined in:
lib/celluloid/timers.rb

Overview

Low precision timers implemented in pure Ruby

Instance Method Summary collapse

Constructor Details

#initializeTimers

Returns a new instance of Timers.



4
5
6
# File 'lib/celluloid/timers.rb', line 4

def initialize
  @timers = []
end

Instance Method Details

#add(interval, recurring = false, &block) ⇒ Object

Call the given block after the given interval



9
10
11
# File 'lib/celluloid/timers.rb', line 9

def add(interval, recurring = false, &block)
  Timer.new(self, interval, recurring, block)
end

#cancel(timer) ⇒ Object

Remove a given timer from the set we’re monitoring



44
45
46
# File 'lib/celluloid/timers.rb', line 44

def cancel(timer)
  @timers.delete timer
end

#empty?Boolean

Are there any timers pending?

Returns:

  • (Boolean)


49
50
51
# File 'lib/celluloid/timers.rb', line 49

def empty?
  @timers.empty?
end

#fireObject

Fire all timers that are ready



28
29
30
31
32
33
34
35
36
# File 'lib/celluloid/timers.rb', line 28

def fire
  return if @timers.empty?

  time = Time.now + Timer::QUANTUM
  while not empty? and time > @timers.first.time
    timer = @timers.shift
    timer.call
  end
end

#index(timer) ⇒ Object

Index where a timer would be located in the sorted timers array



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/celluloid/timers.rb', line 54

def index(timer)
  l, r = 0, @timers.size - 1

  while l <= r
    m = (r + l) / 2
    if timer < @timers.at(m)
      r = m - 1
    else
      l = m + 1
    end
  end
  l
end

#insert(timer) ⇒ Object

Insert a timer into the active timers



39
40
41
# File 'lib/celluloid/timers.rb', line 39

def insert(timer)
  @timers.insert(index(timer), timer)
end

#waitObject

Wait for the next timer and fire it



14
15
16
17
18
19
20
# File 'lib/celluloid/timers.rb', line 14

def wait
  return if @timers.empty?

  interval = wait_interval
  sleep interval if interval >= Timer::QUANTUM
  fire
end

#wait_intervalObject

Interval to wait until when the next timer will fire



23
24
25
# File 'lib/celluloid/timers.rb', line 23

def wait_interval
  @timers.first.time - Time.now unless empty?
end