Module: FrenzyBunnies::Worker::ClassMethods

Defined in:
lib/frenzy_bunnies/worker.rb

Instance Method Summary collapse

Instance Method Details

#from_queue(q, opts = {}) ⇒ Object



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

def from_queue(q, opts={})
  @queue_name = q
  @queue_opts = opts
end

#jobs_statsObject



83
84
85
# File 'lib/frenzy_bunnies/worker.rb', line 83

def jobs_stats
  Hash[ @jobs_stats.map{ |k,v| [k, v.value] } ].merge({ :since => @working_since.to_i })
end

#queue_optsObject



79
80
81
# File 'lib/frenzy_bunnies/worker.rb', line 79

def queue_opts
  @queue_opts
end

#start(context) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/frenzy_bunnies/worker.rb', line 22

def start(context)
  @jobs_stats = { :failed => Atomic.new(0), :passed => Atomic.new(0) }
  @working_since = Time.now

  @logger = context.logger

  @queue_opts[:prefetch] ||= 10
  @queue_opts[:durable] ||= false
  @queue_opts[:timeout_job_after] = 5 if @queue_opts[:timeout_job_after].nil?
  @queue_opts[:handler] ||= FrenzyBunnies::Handlers::Oneshot

  if @queue_opts[:threads]
    @thread_pool = MarchHare::ThreadPools.fixed_of_size(@queue_opts[:threads])
  else
    @thread_pool = MarchHare::ThreadPools.dynamically_growing
  end

  q = context.queue_factory.build_queue(@queue_name, @queue_opts)

  say "#{@queue_opts[:threads] ? "#{@queue_opts[:threads]} threads " : ''}with #{@queue_opts[:prefetch]} prefetch on <#{@queue_name}>."

  q.subscribe(:ack => true, :blocking => false, :executor => @thread_pool) do |headers, msg|
    worker = new
    handler = @queue_opts[:handler].new(headers.channel, q, @logger, { queue_options: @queue_opts })
    begin
      Timeout::timeout(@queue_opts[:timeout_job_after]) do
        if worker.work(msg)
          handler.acknowledge(headers, msg)
          incr! :passed
        else
          handler.reject(headers, msg)
          incr! :failed
          error "REJECTED", msg
        end
      end
    rescue Timeout::Error
      handler.timeout(headers, msg)
      incr! :failed
      error "TIMEOUT #{@queue_opts[:timeout_job_after]}s", msg
    rescue
      handler.reject(headers, msg)
      incr! :failed
      error "ERROR #{$!}", msg
    end
  end

  say "workers up."
end

#stopObject



71
72
73
74
75
76
77
# File 'lib/frenzy_bunnies/worker.rb', line 71

def stop
  say "stopping"
  @thread_pool.shutdown_now
  say "pool shutdown"
  # @s.cancel  #for some reason when the channel socket is broken, this is holding the process up and we're zombie.
  say "stopped"
end