Class: Rodbot::Dispatcher

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

Overview

Dispatcher infrastructure to run and supervise tasks

Constant Summary collapse

TRAPS =

Which signals detached processes trap in order to exit

%w(INT TERM).freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(group, refork_delay: 5) ⇒ Dispatcher

Returns a new instance of Dispatcher.

Parameters:

  • group (String)

    name of the group of tasks

  • refork_delay (Integer) (defaults to: 5)

    seconds to wait before re-forking dead tasks



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

def initialize(group, refork_delay: 5)
  @group, @refork_delay = group, refork_delay
  @tasks = {}
end

Instance Attribute Details

#groupString (readonly)

Returns name of the group of tasks.

Returns:

  • (String)

    name of the group of tasks



12
13
14
# File 'lib/rodbot/dispatcher.rb', line 12

def group
  @group
end

#tasksString (readonly)

Returns registered tasks.

Returns:

  • (String)

    registered tasks



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

def tasks
  @tasks
end

Instance Method Details

#interruptObject

Interrupt the registered tasks



63
64
65
66
# File 'lib/rodbot/dispatcher.rb', line 63

def interrupt
  Process.kill('INT', pid_file('supervisor').read.to_i)
rescue Errno::ESRCH
end

#register(task) { ... } ⇒ Object

Register a task

Parameters:

  • task (String)

    task name

Yields:

  • block for the task to run

Returns:

  • self



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rodbot/dispatcher.rb', line 29

def register(task)
  tasks[task] = Proc.new do
    detach task
    unless Rodbot::Log.std?
      logger = Rodbot::Log.logger("dispatcher #{group}.#{task}]")
      $stdout = Rodbot::Log::LoggerIO.new(logger, Logger::INFO)
      $stderr = Rodbot::Log::LoggerIO.new(logger, Logger::WARN)
      $stdin.reopen(File::NULL)
    end
    yield
  end
  self
end

#run(daemonize: false) ⇒ Object

Run the registered tasks

Parameters:

  • daemonize (Boolean) (defaults to: false)

    whether to run and supervise the tasks in the background



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rodbot/dispatcher.rb', line 47

def run(daemonize: false)
  if daemonize
    Process.daemon(false, true)
    detach 'supervisor'
    dispatch
    supervise
  else
    Process.setproctitle("#{group}.supervisor")
    dispatch
    sleep
  end
ensure
  cleanup
end