thuehlinger / daemons

Ruby daemons gem official repository
MIT License
648 stars 71 forks source link

run many workers #62

Open floodico opened 6 years ago

floodico commented 6 years ago

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?

thuehlinger commented 6 years ago

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
jamesarosen commented 2 years ago

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