Class: Aikido::Zen::BackgroundWorker

Inherits:
Object
  • Object
show all
Defined in:
lib/aikido/zen/background_worker.rb

Overview

Generic background worker class backed by queue. Meant to be used by any background process that needs to do heavy tasks.

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ BackgroundWorker

Returns a new instance of BackgroundWorker.

Parameters:

  • block (block)

    A block that receives 1 message directly from the queue



6
7
8
9
# File 'lib/aikido/zen/background_worker.rb', line 6

def initialize(&block)
  @queue = Queue.new
  @block = block
end

Instance Method Details

#enqueue(scan) ⇒ Object



34
35
36
# File 'lib/aikido/zen/background_worker.rb', line 34

def enqueue(scan)
  @queue.push(scan)
end

#restartObject



22
23
24
25
26
# File 'lib/aikido/zen/background_worker.rb', line 22

def restart
  stop
  @queue = Queue.new # re-open the queue
  start
end

#startObject

starts the background thread, blocking the thread until a new messages arrives or the queue is stopped.



13
14
15
16
17
18
19
20
# File 'lib/aikido/zen/background_worker.rb', line 13

def start
  @thread = Thread.new do
    while running? || actions?
      action = wait_for_action
      @block.call(action) unless action.nil?
    end
  end
end

#stopObject

Drain the queue to do not lose any messages



29
30
31
32
# File 'lib/aikido/zen/background_worker.rb', line 29

def stop
  @queue.close # stop accepting messages
  @thread.join # wait for the queue to be drained
end