merged cont.
[opensuse:yast-rest-service.git] / webyast / vendor / plugins / delayed_job / lib / delayed / worker.rb
1 module Delayed
2   class Worker
3     SLEEP = 5
4
5     cattr_accessor :logger
6     self.logger = if defined?(Merb::Logger)
7       Merb.logger
8     elsif defined?(RAILS_DEFAULT_LOGGER)
9       RAILS_DEFAULT_LOGGER
10     end
11
12     def initialize(options={})
13       @quiet = options[:quiet]
14       Delayed::Job.min_priority = options[:min_priority] if options.has_key?(:min_priority)
15       Delayed::Job.max_priority = options[:max_priority] if options.has_key?(:max_priority)
16     end
17
18     def start
19       say "*** Starting job worker #{Delayed::Job.worker_name}"
20
21       trap('TERM') { say 'Exiting...'; $exit = true }
22       trap('INT')  { say 'Exiting...'; $exit = true }
23
24       loop do
25         result = nil
26
27         realtime = Benchmark.realtime do
28           result = Delayed::Job.work_off
29         end
30
31         count = result.sum
32
33         break if $exit
34
35         if count.zero?
36           sleep(SLEEP)
37         else
38           say "#{count} jobs processed at %.4f j/s, %d failed ..." % [count / realtime, result.last]
39         end
40
41         break if $exit
42       end
43
44     ensure
45       Delayed::Job.clear_locks!
46     end
47
48     def say(text)
49       puts text unless @quiet
50       logger.info text if logger
51     end
52
53   end
54 end