【问题标题】:Ruby daemon script only runs onceRuby 守护程序脚本只运行一次
【发布时间】:2011-01-05 16:44:22
【问题描述】:

我编写了一个 ruby​​ NFC 阅读器脚本并使用 daemons gem 对其进行了守护。除了脚本只运行一次之外,一切都很好......

守护进程.rb

require 'rubygems'
require 'daemons'

pwd  = File.dirname(File.expand_path(__FILE__))
file = pwd + '/touchatag.rb'

Daemons.run_proc(
  'touchatag_project_daemon', # name of daemon
  :dir_mode => :normal,
  :dir => File.join(pwd, 'tmp/pids'), # directory where pid file will be stored
  :backtrace => true,
  :monitor => true,
  :log_output => true
) do
  exec "ruby #{file}"
end

touchatag.rb

quire 'rubygems'
require 'nfc'
require 'httparty'

class TagAssociator
  include HTTParty
  base_uri 'localhost:3000'
end

NFC.instance.find do |tag|
  puts "Processing tag..."
  TagAssociator.post('/answers/answer', :query => {:uid => tag.uid})
end

这很好用,我在我的应用程序中收到了 tag.uid。但是当我扫描另一个 RFID 标签时,脚本不会再次运行...

有谁知道如何调整它“永远”运行并在守护程序停止时停止的脚本?

谢谢

更新

我更新了我的 daemon.rb 脚本:

require 'rubygems'
require 'daemons'

options = {
  :app_name   => "touchatag_project_daemon",
  :ARGV       => ['start', '-f', '--', 'param_for_myscript'],
  :dir_mode   => :script,
  :dir        => 'tmp/pids',
  :multiple   => true,
  :ontop      => true,
  # :mode       => :exec,
  :backtrace  => true,
  :monitor    => true
}

Daemons.run(File.join(File.dirname(__FILE__), '/touchatag.rb'), options)

但它只运行一次...我没有其他建议?

【问题讨论】:

    标签: ruby-on-rails ruby rubygems daemon irb


    【解决方案1】:

    您几乎肯定想使用Daemon.run。如果您想将代码从 touchtag.rb 移动到 Daemon.rbrun_proc 会很有用。

    http://daemons.rubyforge.org/classes/Daemons.html#M000004

    【讨论】:

    • 对不起,我忘了提到你需要将你的 touchtag 代码包装在一个循环中(可能在其中包含睡眠或其他东西)。请注意守护程序示例如何始终出现在 loop { ... }sleep 5 等中。