4

I have some ruby code like this:

result1 = function_1(params)
result2 = function_2(params)
result3 = function_3(params)

But sometimes some of them can take too much time to work (this functions are depends on internet connection speed). I need to terminate execution of function if it takes more then 5 second. How I should do it with ruby-way?

Alve
  • 1,315
  • 2
  • 17
  • 16

2 Answers2

20
require 'timeout'
timeout_in_seconds = 20
begin
  Timeout::timeout(timeout_in_seconds) do
    #Do something that takes long time
  end
rescue Timeout::Error
  # Too slow!!
end
Erez Rabih
  • 15,562
  • 3
  • 47
  • 64
7

You could use Timeout.

require 'timeout'
status = Timeout::timeout(5) {
  # Something that should be interrupted if it takes too much time...
}
xdazz
  • 158,678
  • 38
  • 247
  • 274