Nick Ginanto
Nick Ginanto

Reputation: 32120

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

Upvotes: 1

Views: 353

Answers (2)

Stefan
Stefan

Reputation: 114138

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

Upvotes: 3

sawa
sawa

Reputation: 168071

require "timeout"
begin
  Timeout.timeout(30) do
    $redis.something
  end
rescue => e
  log_it
end

Upvotes: 2

Related Questions