Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate ruby function execution if it takes too long time to work?

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?

like image 577
Alve Avatar asked Nov 27 '22 21:11

Alve


1 Answers

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
like image 179
Erez Rabih Avatar answered Dec 15 '22 05:12

Erez Rabih