Class: Adrian::Dispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/adrian/dispatcher.rb

Direct Known Subclasses

GirlFridayDispatcher

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Dispatcher

Returns a new instance of Dispatcher.



7
8
9
10
11
12
13
# File 'lib/adrian/dispatcher.rb', line 7

def initialize(options = {})
  @failure_handler     = FailureHandler.new
  @stop_when_done      = !!options[:stop_when_done]
  @stop_when_signalled = options.fetch(:stop_when_signalled, true)
  @sleep               = options[:sleep] || 0.5
  @options             = options
end

Instance Attribute Details

#runningObject (readonly)

Returns the value of attribute running.



5
6
7
# File 'lib/adrian/dispatcher.rb', line 5

def running
  @running
end

Instance Method Details

#delegate_work(item, worker_class) ⇒ Object



59
60
61
62
63
# File 'lib/adrian/dispatcher.rb', line 59

def delegate_work(item, worker_class)
  worker = worker_class.new(item)
  worker.report_to(self)
  worker.perform
end

#on_done(&blk) ⇒ Object



19
20
21
# File 'lib/adrian/dispatcher.rb', line 19

def on_done(&blk)
  @failure_handler.add_rule(nil, &blk)
end

#on_failure(*exceptions, &blk) ⇒ Object



15
16
17
# File 'lib/adrian/dispatcher.rb', line 15

def on_failure(*exceptions, &blk)
  @failure_handler.add_rule(*exceptions, &blk)
end

#start(queue, worker_class) ⇒ Object



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
# File 'lib/adrian/dispatcher.rb', line 23

def start(queue, worker_class)
  trap_stop_signals if @stop_when_signalled
  @running = true

  while @running do
    begin
      item = queue.pop
    rescue Adrian::Queue::ItemTooOldError => e
      if handler = @failure_handler.handle(e)
        handler.call(e.item, nil, e)
      end
      item = nil
      next
    end

    if item
      delegate_work(item, worker_class)
    else
      if @stop_when_done
        stop
      else
        sleep(@sleep) if @sleep
      end
    end
  end
end

#stopObject



50
51
52
# File 'lib/adrian/dispatcher.rb', line 50

def stop
  @running = false
end

#trap_stop_signalsObject



54
55
56
57
# File 'lib/adrian/dispatcher.rb', line 54

def trap_stop_signals
  Signal.trap('TERM') { stop }
  Signal.trap('INT')  { stop }
end

#work_done(item, worker, exception = nil) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/adrian/dispatcher.rb', line 65

def work_done(item, worker, exception = nil)
  if handler = @failure_handler.handle(exception)
    handler.call(item, worker, exception)
  else
    raise exception if exception
  end
end