The use of Python to write some network services, when the network is not good, or resource consumption, task congestion, the situation will always throw some exceptions, the current task is terminated, you can use the @ decorator, write a retry of the adorner, so compare python!
Execution Result:
The code is as follows:
WARNING:root:timed out, retrying in 3 seconds ...
WARNING:root:timed out, retrying in 6 seconds ...
WARNING:root:timed out, retrying in seconds ...
The code is as follows:
#!/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 ()