Use Python to write some network services, when the network situation is not good, or resources occupy too much, the task congestion situation, always throw some exceptions, the current task is terminated, can be a good use of the @ Adorner, write a retry of the adorner, so more python!
Execution results:
Copy Code code 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 ...
Copy Code code 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 ()