开发者

Are rails timers reliable when using Net::HTTP?

When reading data from a potentially slow website, I want to ensure that get_response can not hang, and so added a timer to timeout after x seconds. So far, s开发者_JS百科o good. I then read http://ph7spot.com/musings/system-timer which illustrates that in certain situations timer.rb doesn't work due to ruby's implementation of threads.

Does anyone know if this is one of these situations?

url = URI.parse(someurl)

begin
    Timeout::timeout(30) do 
        response = Net::HTTP.get_response(url)
        @responseValue = CGI.unescape(response.body)
    end 
rescue Exception => e 
    dosomething
end


well, first of all Timeout is not a class defined in Rails but in Ruby, second, Timeout is not reliable in cases when you make system calls.

Ruby uses what it's so called Green Threads. Let's suppose you have 3 threads, you think all of them will run in parallel but if one of the threads makes a syscall all the rest of the threads will be blocked until the syscall finishes, in this case Timeout won't work as expected, so it's always better to use something reliable like SystemTimer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜