Python retries the decorator example
- 2020-04-02 13:23:49
- OfStack
When using python to write some network services, when the network is not good, or the resources are too much, task congestion, there will always be some exceptions, the current task is terminated, you can make good use of the @ decorator, write a retry decorator, so as to compare python!
Execution results:
WARNING:root:timed out, Retrying in 3 seconds...
WARNING:root:timed out, Retrying in 6 seconds...
WARNING:root:timed out, Retrying in 12 seconds...
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# tanyewei@gmail.com
# 2014/01/27 10:36
import time
import logging
import socket
from functools import wraps
logging.basicConfig(level=logging.DEBUG)
def retry(MyException, tries=4, delay=3, backoff=2, logger=None):
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except MyException as ex:
msg = "%s, Retrying in %d seconds..." % (str(ex), mdelay)
if logger:
logger.warning(msg)
else:
print msg
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return str(ex)
return f_retry
return deco_retry
@retry(Exception, logger=logging)
def check():
sk = socket.socket()
sk.settimeout(5)
sk.connect(('6.6.6.6', 80))
if __name__ == "__main__":
check()