Ruby em http请求-我应该将EventMachine.stop放在哪里?

Ruby em http请求-我应该将EventMachine.stop放在哪里?,ruby,http,eventmachine,Ruby,Http,Eventmachine,我希望每10秒钟迭代一次JSON-API,如果在JSON数据中找到某个键,则使用相同的连接(keepalive)执行第二次HTTP请求。如果我没有在我的代码中放置EM.stop,程序将在req1.callback中完成处理后停止等待 如果我将EM.stop放入req2.callback中,它将正常工作并按预期进行迭代 但是,如果JSON文档没有包含键foobar,则程序在req1.callback中完成处理后会停止等待 如果我在req1.callback中的最后一行添加EM.stop,那么如果J

我希望每10秒钟迭代一次JSON-API,如果在JSON数据中找到某个键,则使用相同的连接(keepalive)执行第二次HTTP请求。如果我没有在我的代码中放置
EM.stop
,程序将在req1.callback中完成处理后停止等待

如果我将
EM.stop
放入
req2.callback
中,它将正常工作并按预期进行迭代

但是,如果JSON文档没有包含键
foobar
,则程序在req1.callback中完成处理后会停止等待

如果我在req1.callback中的最后一行添加
EM.stop
,那么如果JSON文档具有键
foobar
,则req2.callback将中止

如果JSON文档中有我想要的内容,我应该如何正确地放置
EM.stop
,使其迭代

require 'eventmachine'
require 'em-http'

loop do    
  EM.run do
    c = EM::HttpRequest.new 'http://api.example.com/'

    req1 = c.get :keepalive => true
    req1.callback do
      document = JSON.parse req1.response
      if document.has_key? foobar   
        req2 = c.get :path => '/data/'
        req2.callback do
          puts [:success, 2, req2]
          puts "\n\n\n"
          EM.stop
        end
      end
    end
  end

  sleep 10
end

如果要使用计时器,应使用EM提供的实际计时器支持:

例如:

require 'eventmachine'
require 'em-http'

EM.run do
  c = EM::HttpRequest.new 'http://google.com/'
  EM.add_periodic_timer(10) do
    # Your logic to be run every 10 seconds goes here!
  end
end

这样,您就可以让EventMachine一直运行,而不必每10秒启动/停止一次。

刚刚尝试过这个,但它似乎从未进入
req1.callback
。有什么建议吗?谢谢!在我接受最合适的答案之前,我会试试这个。完美的解决方案!使用这种内置功能比使用无限循环和睡眠“破解”它更有意义。
require 'eventmachine'
require 'em-http'

EM.run do
  c = EM::HttpRequest.new 'http://google.com/'
  EM.add_periodic_timer(10) do
    # Your logic to be run every 10 seconds goes here!
  end
end