Class: Workers::Worker

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/workers/worker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#concat_e, #log_debug, #log_error, #log_info, #log_warn

Constructor Details

#initialize(options = {}) ⇒ Worker

Returns a new instance of Worker.



7
8
9
10
11
12
13
14
15
# File 'lib/workers/worker.rb', line 7

def initialize(options = {})
  @logger = Workers::LogProxy.new(options[:logger])
  @input_queue = options[:input_queue] || Queue.new
  @thread = Thread.new { start_event_loop }
  @exception_callback = options[:on_exception]
  @die_on_exception = options.include?(:die_on_exception) ? options[:die_on_exception] : true

  nil
end

Instance Attribute Details

#exceptionObject

Returns the value of attribute exception.



5
6
7
# File 'lib/workers/worker.rb', line 5

def exception
  @exception
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/workers/worker.rb', line 54

def alive?
  @thread && @thread.alive?
end

#dispose(max_wait = nil) ⇒ Object



49
50
51
52
# File 'lib/workers/worker.rb', line 49

def dispose(max_wait = nil)
  shutdown
  join(max_wait)
end

#enqueue(command, data = nil) ⇒ Object



17
18
19
20
21
# File 'lib/workers/worker.rb', line 17

def enqueue(command, data = nil)
  @input_queue.push(Event.new(command, data))

  nil
end

#inspectObject



58
59
60
# File 'lib/workers/worker.rb', line 58

def inspect
  "#<#{self.class.to_s}:0x#{(object_id << 1).to_s(16)} #{alive? ? 'alive' : 'dead'}>"
end

#join(max_wait = nil) ⇒ Object

Raises:



41
42
43
44
45
46
47
# File 'lib/workers/worker.rb', line 41

def join(max_wait = nil)
  raise Workers::JoinError, "Worker can't join itself." if @thread == Thread.current

  return true if !@thread.join(max_wait).nil?

  @thread.kill and return false
end

#killObject



35
36
37
38
39
# File 'lib/workers/worker.rb', line 35

def kill
  @thread.kill

  nil
end

#perform(&block) ⇒ Object



23
24
25
26
27
# File 'lib/workers/worker.rb', line 23

def perform(&block)
  enqueue(:perform, block)

  nil
end

#shutdown(&block) ⇒ Object



29
30
31
32
33
# File 'lib/workers/worker.rb', line 29

def shutdown(&block)
  enqueue(:shutdown, block)

  nil
end