我希望每隔10秒迭代一次JSON-API,如果在JSON-data中找到了某个键,则使用相同的连接(keepalive)执行第二个HTTP请求。如果我没有在我的代码中放置EM.stop,程序会在req1.callback中完成处理后停止等待。
如果我将EM.stop放在req2.callback中,它就可以正常工作并按预期进行迭代。
但是如果JSON-document没有包含密钥foobar,那么在req1.callback中完成处理后,程序会停止等待。
如果我在req1.callback内的最后一行添加EM.stop,如果JSON-document具有键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发布于 2012-04-25 23:07:28
如果要使用计时器,则应该使用EM:http://eventmachine.rubyforge.org/EventMachine.html#M000467提供的实际计时器支持
例如:
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秒启动/停止一次。
发布于 2012-04-25 21:58:56
require 'eventmachine'
require 'em-http'
loop do
EM.run do
c = EM::HttpRequest.new 'http://google.com/'
req1 = c.get :keepalive => true
req1.callback do
begin
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
rescue => e
EM.stop
raise e
end
end
req1.errback do
print "ERROR"
EM.stop
end
end
sleep 10
endhttps://stackoverflow.com/questions/10316882
复制相似问题