Sha256: 97254293b1571104338a17f13aacb6e37b6a732e8c9df5a3c0b6e2a786ddf532
Contents?: true
Size: 1.95 KB
Versions: 1
Compression:
Stored size: 1.95 KB
Contents
module God class TimerEvent attr_accessor :condition, :at def initialize(condition, interval) self.condition = condition self.at = Time.now.to_i + interval end end class Timer INTERVAL = 0.25 attr_reader :events, :timer @@timer = nil def self.get @@timer ||= Timer.new end def self.reset @@timer = nil end # Start the scheduler loop to handle events def initialize @events = [] @mutex = Mutex.new @timer = Thread.new do loop do begin # get the current time t = Time.now.to_i # iterate over each event and trigger any that are due @events.each do |event| if t >= event.at self.trigger(event) @mutex.synchronize do @events.delete(event) end else break end end # sleep until next check sleep INTERVAL rescue Exception => e message = format("Unhandled exception (%s): %s\n%s", e.class, e.message, e.backtrace.join("\n")) applog(nil, :fatal, message) sleep INTERVAL end end end end # Create and register a new TimerEvent with the given parameters def schedule(condition, interval = condition.interval) @mutex.synchronize do @events << TimerEvent.new(condition, interval) @events.sort! { |x, y| x.at <=> y.at } end end # Remove any TimerEvents for the given condition def unschedule(condition) @mutex.synchronize do @events.reject! { |x| x.condition == condition } end end def trigger(event) Hub.trigger(event.condition) end # Join the timer thread def join @timer.join end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
god-0.6.0 | lib/god/timer.rb |