首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >em-http-request -我应该把我的EventMachine.stop放在哪里?

em-http-request -我应该把我的EventMachine.stop放在哪里?
EN

Stack Overflow用户
提问于 2012-04-25 21:37:48
回答 2查看 1K关注 0票数 4

我希望每隔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以使其迭代?

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-25 23:07:28

如果要使用计时器,则应该使用EM:http://eventmachine.rubyforge.org/EventMachine.html#M000467提供的实际计时器支持

例如:

代码语言:javascript
复制
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秒启动/停止一次。

票数 2
EN

Stack Overflow用户

发布于 2012-04-25 21:58:56

代码语言:javascript
复制
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
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10316882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档