简体   繁体   中英

How to skip if method is taking too long

I have a redis call that may take too long due to network issues, up until the call is timed out. That redis call is not important.

Is there a way to wrap that call with something that will check how long it takes and if it takes too long to skip the call (and maybe call some other method to log that)?

something like

check_time(30.seconds) do 
 $redis.something

 if error
   log it
 end
end

You could use Timeout . Here's the example from the documentation:

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

It throws an error if the timeout occurs:

require 'timeout'
begin
  Timeout::timeout(30) {
    $redis.something
  }
rescue Timeout::Error
  # log error
end
require "timeout"
begin
  Timeout.timeout(30) do
    $redis.something
  end
rescue => e
  log_it
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM