Method: MessageBus::TimerThread#queue

Defined in:
lib/message_bus/timer_thread.rb

#queue(delay = 0, &block) ⇒ Object

queue a block to run after a certain delay (in seconds)



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/message_bus/timer_thread.rb', line 75

def queue(delay = 0, &block)
  queue_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) + delay
  job = [queue_time, block]

  @mutex.synchronize do
    i = @jobs.length
    while i > 0
      i -= 1
      current, _ = @jobs[i]
      if current < queue_time
        i += 1
        break
      end
    end
    @jobs.insert(i, job)
    @next = queue_time if i == 0
  end

  unless @thread.alive?
    @mutex.synchronize do
      @thread = Thread.new { do_work } unless @thread.alive?
    end
  end

  if @thread.status == "sleep"
    @thread.wakeup
  end

  Cancelable.new(job)
end