Skip to content

Instantly share code, notes, and snippets.

@shihongzhi
Created August 23, 2012 08:19
Show Gist options
  • Save shihongzhi/3434223 to your computer and use it in GitHub Desktop.
Save shihongzhi/3434223 to your computer and use it in GitHub Desktop.
retry decorator
import time
import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
def deco_retry(f):
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
try_one_last_time = True
while mtries > 1:
try:
return f(*args, **kwargs)
try_one_last_time = False
break
except ExceptionToCheck, e:
msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)
if logger:
logger.warning(msg)
else:
print msg
time.sleep(mdelay)
mtries -= 1
#mdelay *= backoff
#最后再执行一遍
if try_one_last_time:
return f(*args, **kwargs)
return
return f_retry
return deco_retry
@retry(Exception, tries=10)
def helper():
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment