开发者

Dynamic Ruby Daemon Management

开发者 https://www.devze.com 2023-04-01 02:45 出处:网络
I have a Ruby process that listens on a given device. I would like to spin up/down instances of it for different devices with a rails app. Everything I can find for Ruby daemons seems to be based arou

I have a Ruby process that listens on a given device. I would like to spin up/down instances of it for different devices with a rails app. Everything I can find for Ruby daemons seems to be based around a set num开发者_StackOverflow社区ber of daemons running or background processing with message queues.

Should I just be doing this with Kernel.spawn and storing the PIDs in the database? It seems a bit hacky but if there isn't an existing framework that allows me to bring up/down daemons it seems I may not have much choice.


Instead of spawning another script and keeping the PIDs in the database, you can do it all within the same script, using fork, and keeping PIDs in memory. Here's a sample script - you add and delete "worker instances" by typing commands "add" and "del" in console, exiting with "quit":

@pids = []
@counter = 0

def add_process
  @pids.push(Process.fork {
    loop do
      puts "Hello from worker ##{@counter}"
      sleep 1
    end
  })
  @counter += 1
end

def del_process
  return false if @pids.empty?
  pid = @pids.pop
  Process.kill('SIGTERM', pid)
  true
end

def kill_all
  while del_process
  end
end

while cmd = gets.chomp
  case cmd.downcase
  when 'quit'
    kill_all
    exit
  when 'add'
    add_process
  when 'del'
    del_process
  end
end

Of course, this is just an example, and for sending comands and/or monitoring instances you can replace this simple gets loop with a small Sinatra app, or socket interface, or named pipes etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消