I want to iterate over a JSON-API every 10th second, and do a second HTTP-request using the same connection (keepalive) if a certain key was found in the JSON-data. If I do not place EM.stop in my code, the program stops to wait after finishing processing in req1.callback.
If I put EM.stop inside req2.callback it works and is iterating as expected.
But if the JSON-document did not include the key foobar, the program stops to wait after finishing processing in req1.callback.
If I add EM.stop in the last line inside req1.callback, req2.callback is aborted if the JSON-document had the key foobar.
How should I properly place EM.stop to make it iterate if the JSON-document had what I wanted or not?
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
If you want to use a timer, you should use the actual timer support from EM: http://eventmachine.rubyforge.org/EventMachine.html#M000467
For example:
This way, you keep EventMachine running the whole time, instead of having to start/stop it every 10 seconds.