class OmfCommon::Eventloop::Local
Implements a simple eventloop which only deals with timer events
Public Class Methods
new(opts = {}, &block)
click to toggle source
Calls superclass method
OmfCommon::Eventloop::new
# File lib/omf_common/eventloop/local_evl.rb, line 14 def initialize(opts = {}, &block) super @tasks = [] @running = false after(0, &block) if block end
Public Instance Methods
after(delay_sec, &block)
click to toggle source
Execute block after some time
@param [Float] delay_sec in sec
# File lib/omf_common/eventloop/local_evl.rb, line 25 def after(delay_sec, &block) @tasks << [Time.now + delay_sec, block] end
defer(&block)
click to toggle source
Call ‘block’ in the context of a separate thread.
# File lib/omf_common/eventloop/local_evl.rb, line 39 def defer(&block) @logger.note("DEFER") Thread.new do begin block.call() rescue => ex @logger.error "Exception '#{ex}'" @logger.debug ex.backtract.join("\n\t") end end end
every(interval_sec, &block)
click to toggle source
Periodically call block every interval_sec
@param [Float] interval_sec in sec
# File lib/omf_common/eventloop/local_evl.rb, line 33 def every(interval_sec, &block) @tasks << [Time.now + interval_sec, block, :periodic => interval_sec] end
run(&block)
click to toggle source
# File lib/omf_common/eventloop/local_evl.rb, line 56 def run(&block) after(0, &block) if block return if @running @running = true while @running do now = Time.now @tasks = @tasks.sort while @tasks[0] && @tasks[0][0] <= now # execute t = @tasks.shift debug "Executing Task #{t}" block = t[1] block.arity == 0 ? block.call : block.call(self) now = Time.now # Check if periodic if interval = ((t[2] || {})[:periodic]) if (next_time = t[0] + interval) < now warn "Falling behind with periodic task #{t[1]}" next_time = now + interval end @tasks << [next_time, t[1], :periodic => interval] end end # by now, there could have been a few more tasks added, so let's sort again @tasks = @tasks.sort if @tasks.empty? # done @running = false else if (delay = @tasks[0][0] - Time.now) > 0 debug "Sleeping #{delay}" sleep delay end end end end
stop()
click to toggle source
# File lib/omf_common/eventloop/local_evl.rb, line 52 def stop @running = false end