Class: EventMachine::Synchrony::FiberPeriodicTimerIterator

Inherits:
EM::Synchrony::Iterator
  • Object
show all
Defined in:
lib/patch/fiber_periodic_timer_iterator.rb

Instance Method Summary collapse

Constructor Details

#initialize(list, concurrency = 1, timeout = 0) ⇒ FiberPeriodicTimerIterator

set timeout and start point each Fiber will be executed not earlier than once per timeout



8
9
10
11
12
# File 'lib/patch/fiber_periodic_timer_iterator.rb', line 8

def initialize(list, concurrency=1, timeout=0)
  @timeout = timeout
  @next_start = Time.now
  super list, concurrency
end

Instance Method Details

#each(foreach = nil, after = nil, &blk) ⇒ Object

execute each iterator block within its own fiber at particular time offset and auto-advance the iterator after each call



16
17
18
19
20
21
22
23
24
# File 'lib/patch/fiber_periodic_timer_iterator.rb', line 16

def each(foreach=nil, after=nil, &blk)
  fe = Proc.new do |obj, iter|
    Fiber.new do
      sleep
      (foreach || blk).call(obj); iter.next
    end.resume
  end
  super(fe, after)
end

#sleepObject

Sleep if the last request was recently (less then timout period)



27
28
29
30
31
32
33
34
35
# File 'lib/patch/fiber_periodic_timer_iterator.rb', line 27

def sleep
  if @timeout > 0
    now = Time.now
    sleep_time = @next_start - Time.now
    sleep_time = 0 if sleep_time < 0
    @next_start = Time.now + sleep_time + @timeout
    EM::Synchrony.sleep(sleep_time) if sleep_time > 0
  end
end