module Logster::Deferer

Attributes

queue[R]
thread[R]

Public Class Methods

new() click to toggle source
# File lib/logster/scheduler.rb, line 6
def initialize
  @queue = Queue.new
  @mutex = Mutex.new
  @thread = nil
  @enabled = true
end

Public Instance Methods

disable() click to toggle source
# File lib/logster/scheduler.rb, line 13
def disable
  @enabled = false
end
enable() click to toggle source
# File lib/logster/scheduler.rb, line 17
def enable
  @enabled = true
end
schedule(&blk) click to toggle source
# File lib/logster/scheduler.rb, line 21
def schedule(&blk)
  if @enabled
    start_thread if !@thread&.alive?
    @queue << blk
  else
    return if blk == :terminate
    blk.call
  end
end

Private Instance Methods

do_work() click to toggle source
# File lib/logster/scheduler.rb, line 41
def do_work
  while true
    blk = @queue.pop
    # we need to be able to break the loop so that the new
    # thread "finishes" and let us test this code.
    break if blk == :terminate
    blk.call
  end
end
start_thread() click to toggle source
# File lib/logster/scheduler.rb, line 33
def start_thread
  @mutex.synchronize do
    if !@thread&.alive?
      @thread = Thread.new { do_work }
    end
  end
end