Class: NSQ::Timer
- Inherits:
-
Object
- Object
- NSQ::Timer
- Defined in:
- lib/nsq/timer.rb
Overview
:nodoc:
Instance Method Summary collapse
- #add(interval, &block) ⇒ Object
-
#initialize(selector) ⇒ Timer
constructor
A new instance of Timer.
-
#next_interval ⇒ Object
Execute any necessary procs and return the next interval or nil if no procs.
Constructor Details
#initialize(selector) ⇒ Timer
Returns a new instance of Timer.
6 7 8 9 10 |
# File 'lib/nsq/timer.rb', line 6 def initialize(selector) @selector = selector @proc_array = [] @mutex = Mutex.new end |
Instance Method Details
#add(interval, &block) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/nsq/timer.rb', line 12 def add(interval, &block) new_run_at = Time.now + interval @mutex.synchronize do old_next_pair = @proc_array.first @proc_array << [new_run_at, block] # Sort the proc_array so the next one to run is at the front @proc_array.sort_by { |pair| pair.first } new_next_pair = @proc_array.first # If the next proc has changed, then wakeup the selector so we can set the new next time @selector.wakeup unless new_next_pair == old_next_pair end end |
#next_interval ⇒ Object
Execute any necessary procs and return the next interval or nil if no procs
26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/nsq/timer.rb', line 26 def next_interval now = Time.now @mutex.synchronize do loop do run_at, proc = @proc_array.first return nil unless run_at interval = run_at - now return interval if interval > 0 proc.call @proc_array.shift end end end |