daemons icon indicating copy to clipboard operation
daemons copied to clipboard

run many workers

Open floodico opened this issue 7 years ago • 2 comments

hello there. I try to run 2 my workers: ["first_worker.rb", "second_worker.rb"].each { |worker| Daemons.run(worker) } But is running only first. Why? How can i run all my workers?

floodico avatar Feb 01 '18 13:02 floodico

This is because Daemons.run full transfers control to daemons and does not return. For your scenario, it might be more helpful to use procs, see third example in daemons.rb:

# this is my_app.rb
require 'daemons'

task1 = Daemons.call(:multiple => true) do
  # first server task

  loop do
    conn = accept_conn()
    serve(conn)
  end
end

task2 = Daemons.call do
  # second server task

  loop do
    something_different()
  end
end

# the parent process continues to run

# we can even control our tasks, for example stop them
task1.stop
task2.stop

exit

thuehlinger avatar Feb 05 '18 19:02 thuehlinger

If you want to be able to use a manager to control the tasks as a group, I've had some success with run_proc:

# my_processes.rb
require 'daemons'
Daemons.run_proc('foo', monitor: true) do
  loop do
    puts "foo alive"
    sleep 1
  end
end

Daemons.run_proc('bar', monitor: true) do
  loop do
    puts "bar alive"
    sleep 1
  end
end

Then you can start, stop, and get status:

$ ruby my_processes.rb start
$ ruby my_processes.rb stop

jamesarosen avatar Dec 22 '21 01:12 jamesarosen