【问题标题】:How to skip if method is taking too long如果方法花费的时间太长,如何跳过
【发布时间】:2014-01-05 01:30:20
【问题描述】:

由于网络问题,我的 redis 调用可能需要很长时间,直到调用超时。那个 redis 调用并不重要。

有没有办法用一些东西来包装这个调用,检查它需要多长时间以及跳过调用是否需要太长时间(并且可能调用其他方法来记录它)?

类似

check_time(30.seconds) do 
 $redis.something

 if error
   log it
 end
end

【问题讨论】:

    标签: ruby timeout


    【解决方案1】:

    您可以使用Timeout。这是文档中的示例:

    require 'timeout'
    status = Timeout::timeout(5) {
      # Something that should be interrupted if it takes more than 5 seconds...
    }
    

    如果发生超时则抛出错误:

    require 'timeout'
    begin
      Timeout::timeout(30) {
        $redis.something
      }
    rescue Timeout::Error
      # log error
    end
    

    【讨论】:

    • 超时是要走的路...但是要careful,请注意redis-rb接受超时选项also
    【解决方案2】:
    require "timeout"
    begin
      Timeout.timeout(30) do
        $redis.something
      end
    rescue => e
      log_it
    end
    

    【讨论】:

      猜你喜欢
      • 2016-12-28
      • 1970-01-01
      • 2023-03-10
      • 2022-12-18
      • 2014-07-29
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多