Module: FrenzyBunnies::Worker::ClassMethods

Defined in:
lib/frenzy_bunnies/worker.rb

Instance Method Summary collapse

Instance Method Details

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



21
22
23
24
# File 'lib/frenzy_bunnies/worker.rb', line 21

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

#jobs_statsObject



88
89
90
# File 'lib/frenzy_bunnies/worker.rb', line 88

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

#queue_optsObject



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

def queue_opts
  @queue_opts
end

#start(context) ⇒ Object



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
70
71
72
73
74
# File 'lib/frenzy_bunnies/worker.rb', line 26

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

  @logger = context.logger

  queue_name = "#{@queue_name}_#{context.env}"

  @queue_opts[:prefetch] ||= 10
  @queue_opts[:durable] ||= false
  @queue_opts[:timeout_job_after] ||=5

  if @queue_opts[:threads]
    @thread_pool = Executors.new_fixed_thread_pool(@queue_opts[:threads])
  else
    @thread_pool = Executors.new_cached_thread_pool
  end

  q = context.queue_factory.build_queue(queue_name, @queue_opts[:prefetch], @queue_opts[:durable])
  @s = q.subscribe(:ack => true)

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

  @s.each(:blocking => false, :executor => @thread_pool) do |h, msg|
    wkr = new
    begin
      Timeout::timeout(@queue_opts[:timeout_job_after]) do
        if(wkr.work(msg))
          h.ack
          incr! :passed
        else
          h.reject
          incr! :failed
          error "REJECTED", msg
        end
      end
    rescue Timeout::Error
      h.reject
      incr! :failed
      error "TIMEOUT #{@queue_opts[:timeout_job_after]}s", msg
    rescue
      h.reject
      incr! :failed
      error "ERROR #{$!}", msg
    end
  end

  say "workers up."
end

#stopObject



76
77
78
79
80
81
82
# File 'lib/frenzy_bunnies/worker.rb', line 76

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