Class: Magent::Processor

Inherits:
Object
  • Object
show all
Defined in:
lib/magent/processor.rb

Instance Method Summary collapse

Constructor Details

#initialize(channel, identity = "#{channel.name}-#{Socket.gethostname.split('.')[0]}") ⇒ Processor

Returns a new instance of Processor.



3
4
5
6
7
8
9
# File 'lib/magent/processor.rb', line 3

def initialize(channel, identity = "#{channel.name}-#{Socket.gethostname.split('.')[0]}")
  @channel = channel
  @shutdown = false
  @identity = identity

  @channel.on_start(identity)
end

Instance Method Details

#run!(service = true) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
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
# File 'lib/magent/processor.rb', line 11

def run!(service = true)
  processed_messages = 0
  delay = 0

  trap('TERM') { shutdown!; exit 0 }
  trap('SIGINT') { shutdown!; exit 0 }

  loop do
    break if @shutdown

    message = @channel.dequeue
    begin
      t = Time.now
      if message && @channel.process!(message)
        puts "Processed #{message.inspect}"

        @channel.on_job_processed(@channel.current_job, Time.now - t, @identity)

        delay = 0
        processed_messages += 1
        if processed_messages > 20
          processed_messages = 0
          GC.start
        end
      else
        delay += 0.1 if delay <= 5
      end
    rescue SystemExit
    rescue Exception => e
      $stderr.puts "Error processing #{message.inspect} => #{e.message}.\n#{e.backtrace.join("\n\t")}"
      @channel.on_job_failed(@identity)

      if !@channel.retry_current_job
        $stderr.puts "Cannot retry job because it has been retried #{@channel.current_job['retries']} times"
        @channel.failed(:error => e.message, :message => message, :backtrace => e.backtrace, :date => Time.now.utc)
      end
    ensure
    end

    break if !service

    sleep (delay*100.0).to_i/100.0
  end
end

#shutdown!Object



56
57
58
59
60
61
62
# File 'lib/magent/processor.rb', line 56

def shutdown!
  @shutdown = true
  @channel.on_quit(@identity)

  @channel.on_shutdown if @channel.respond_to?(:on_shutdown)
  $stderr.puts "Shutting down..."
end