使用 Net::HTTP 时 Rails 计时器可靠吗?

发布于 2024-08-24 19:01:42 字数 515 浏览 3 评论 0原文

当从可能很慢的网站读取数据时,我想确保 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雅心素梦 2024-08-31 19:01:42

首先,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文