【问题标题】:How do I loop the restart of a daemon?如何循环重启守护进程?
【发布时间】:2012-10-19 10:04:46
【问题描述】:

我正在尝试使用 Ruby 的 daemon gem 并循环重启具有自己循环的守护程序。我的代码现在看起来像这样:

require 'daemons'

while true
  listener = Daemons.call(:force => true) do
    users = accounts.get_updated_user_list

    TweetStream::Client.new.follow(users) do |status|
      puts "#{status.text}"
    end
  end
  sleep(60)
  listener.restart
end

运行它会出现以下错误(60 秒后):

undefined method `restart' for #<Daemons::Application:0x007fc5b29f5658> (NoMethodError)

所以很明显Daemons.call 不会像我想的那样返回一个可控的守护进程。我需要做什么才能正确设置它。守护进程是正确的工具吗?

【问题讨论】:

  • 您的意图到底是什么?我不知道你想做什么,但我猜你走错了路。为什么要每 60 秒重启一次守护进程?
  • 我正在使用 Tweetstream gem 从用户列表中获取推文。每分钟(或 10 分钟或其他任何时间)我都想重新生成该用户列表,然后重新启动 Tweetstream 客户端。我将更新示例代码以更好地反映这一点。

标签: ruby daemons tweetstream


【解决方案1】:

我认为这就是你所追求的,虽然我还没有测试过。

class RestartingUserTracker
  def initialize
    @client = TweetStream::Client.new
  end

  def handle_status(status)
    # do whatever it is you're going to do with the status
  end

  def fetch_users
    accounts.get_updated_user_list
  end

  def restart
    @client.stop_stream
    users = fetch_users
    @client.follow(users) do |status|
      handle_status(status)
    end
  end
end

EM.run do
  client = RestartingUserTracker.new
  client.restart

  EM::PeriodicTimer.new(60) do
    client.restart
  end
end

它是这样工作的:

TweetStream 在内部使用 EventMachine,作为一种永久轮询 API 并处理响应的方式。我明白您为什么会感到卡住了,因为普通的 TweetStream API 会永远阻塞,并且无法让您随时进行干预。但是,TweetStream 确实允许您在同一事件循环 中设置其他内容。在你的情况下,一个计时器。我在这里找到了有关如何执行此操作的文档:https://github.com/intridea/tweetstream#removal-of-on_interval-callback

通过启动我们自己的 EventMachine 反应器,我们能够将自己的代码注入反应器并使用 TweetStream。在本例中,我们使用了一个简单的计时器,它每 60 秒重新启动一次客户端。

EventMachine 是一种称为反应器模式的实现。如果您想完全理解和维护这段代码,最好找到一些关于它的资源并获得全面的理解。反应器模式非常强大,但一开始可能很难掌握。

但是,此代码应该可以帮助您入门。另外,我会考虑将 RestartingUserTracker 重命名为更合适的名称。

【讨论】:

  • 这看起来真不错!看来我也应该了解更多有关 EventMachine 的信息。明天我将对此进行测试,然后结束这个问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 2013-01-09
  • 2022-01-06
相关资源
最近更新 更多