Class: Astrotrain::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/astrotrain/worker.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Worker

Returns a new instance of Worker.



10
11
12
13
14
15
# File 'lib/astrotrain/worker.rb', line 10

def initialize(options = {})
  @name            = options[:name]  || "pid:#{Process.pid}"
  @pid             = options[:pid]   || File.join(Astrotrain.root, 'log', 'astrotrain_job.pid')
  @sleep_duration  = options[:sleep] || 5
  @logger          = options.key?(:logger) ? options[:logger] : STDOUT
end

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



4
5
6
# File 'lib/astrotrain/worker.rb', line 4

def logger
  @logger
end

#nameObject

Returns the value of attribute name.



4
5
6
# File 'lib/astrotrain/worker.rb', line 4

def name
  @name
end

#sleep_durationObject

Returns the value of attribute sleep_duration.



4
5
6
# File 'lib/astrotrain/worker.rb', line 4

def sleep_duration
  @sleep_duration
end

Class Method Details

.start(options = {}, &block) ⇒ Object



6
7
8
# File 'lib/astrotrain/worker.rb', line 6

def self.start(options = {}, &block)
  new(options).run(&block)
end

Instance Method Details

#process_emailsObject



23
24
25
26
27
28
29
30
31
32
# File 'lib/astrotrain/worker.rb', line 23

def process_emails
  files = 0
  Dir.foreach(Message.queue_path) do |f|
    next if f =~ /^\.{1,2}$/
    files += 1
    file = File.join(Message.queue_path, f)
    Message.receive_file(file)
  end
  files
end

#run(&block) ⇒ Object

override this to perform other tasks in the astrotrain job loop



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

def run(&block)
  block ||= lambda { |w| w.process_emails }
  setup(&block)
end

#say(s) ⇒ Object



34
35
36
# File 'lib/astrotrain/worker.rb', line 34

def say(s)
  @logger << "#{s}\n" if @logger
end

#setupObject



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
# File 'lib/astrotrain/worker.rb', line 38

def setup
  say "*** Starting Astrotrain::Worker #{@name}"
  FileUtils.mkdir_p File.dirname(@pid)

  File.open(@pid, 'w') { |f| f << Process.pid.to_s }
   
  trap('TERM') { puts 'Exiting...'; $exit = true }
  trap('INT')  { puts 'Exiting...'; $exit = true }

  loop do
    count    = nil
    realtime = Benchmark.realtime { count = yield(self) }

    break if $exit

    if count.zero?
      sleep(@sleep_duration)
    else
      puts "#{count} mails processed at %.4f m/s ..." % [count / realtime]
    end

    break if $exit
  end
ensure
  FileUtils.rm(@pid) rescue nil
end