def TryFunctionWithTimeout(func, error_handler, num_tries,
sleep_between_attempt_secs, *args, **kwargs):
"""The function tries to run a function without any exception.
The function tries for a certain number of tries. If it cannot succeed,
it raises BenchmarkError.
Args:
func: the function to try running without exception
error_handler: the exception that the function should catch and keep trying.
num_tries: number of tries it should make before raising the final
exception
sleep_between_attempt_secs: number of seconds to sleep between each retry
*args: arguments to the function
**kwargs: named arguments to the function
Raises:
BenchmarkError: When all tries are failed.
"""
count = num_tries
while count > 0:
try:
count -= 1
ret_val = func(*args, **kwargs)
if not ret_val:
return
else:
print ret_val
except error_handler as e:
print e
print ("Problem running function, {}. Trying again after"
" {}s. Total tries left: {}.").format(func,
sleep_between_attempt_secs,
count)
time.sleep(sleep_between_attempt_secs)
raise BenchmarkError("All tries failed.")
评论列表
文章目录