Reputation: 26008
I want to do a retry operation in ruby with a small distinction: I want to do it with a timer and there might be no exceptions. The timer should measure the time all attempts have taken
Here's an example without one, but it uses "rescue" which means it assumes there'll be an exception, whereas in my code there might not be one.
retry_count = 5
begin
#something
rescue
retry_count -= 1
if retry_count > 0
retry
end
end
My goal is just to make sure that all the attempts I make won't exceed a certain period of time.
Note that #something
is an IO operation in can take different time in different attempts.
How can I properly introduce a timer here so that I won't only check the retry count but also that a certain period of time hasn't been passed yet?
Upvotes: 0
Views: 778
Reputation: 121000
retry_count = 5
timeslice = 3 # sec
begin
started = Time.now
#something
rescue
retry_count -= 1
if retry_count > 0
sleep [timeslice - (Time.now - started), 0].max
# or, alternatively:
# time_left = timeslice - (Time.now - started)
# sleep timeleft if timeleft > 0
retry
end
end
Upvotes: 2