Reputation: 11121
I can use this code to introduce timeout for my functions
require 'timeout'
Timeout::timeout(timeout_period) do
run_some_code
rescue => err
do_something_with err
# and maybe the below?
raise
end
How can I create another function my_timeout
that I can reuse for such purpose? I want to be able to specify that the called function in case of timeout "needs" to be run again.
So then I would call my_timeout
like my_timeout('function name',int_how_many_times_to repeat_if times_out)
I use ruby 1.9.3p194 (2012-04-20) [i386-mingw32]
on Windows7
Upvotes: 1
Views: 105
Reputation: 1356
def my_timeout repeat_n_times, timeout_period, &block
Timeout::timeout timeout_period, &block
rescue Timeout::Error => timeout_error
repeat_n_times -= 1
if repeat_n_times > 0
retry
else
raise timeout_error
end
end
# Example
# execute the block with a timeout of 30 and repeat up to 5 times
my_timeout 5, 30 do
# do the heavy work
end
Upvotes: 1