使用 Net::HTTP 时 Rails 计时器可靠吗?
当从可能很慢的网站读取数据时,我想确保 get_response 不会挂起,因此添加了一个计时器以在 x 秒后超时。到目前为止,一切都很好。然后我阅读了 http://ph7spot.com/musings/system-timer ,其中说明了这一点某些情况下,由于 ruby 的线程实现,timer.rb 无法工作。
有谁知道这是否是这些情况之一?
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
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, so 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,Timeout 不是 Rails 中定义的类,而是 Ruby 中定义的类,其次,当您进行系统调用时,Timeout 并不可靠。
Ruby 使用所谓的“绿色线程”。假设您有 3 个线程,您认为所有线程都将并行运行,但如果其中一个线程进行系统调用,则所有其余线程将被阻塞,直到系统调用完成,在这种情况下,超时将无法按预期工作,所以最好使用像 SystemTimer 这样可靠的东西。
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.