Python always throws some exceptions when writing some network services, and the current task is terminated. use the @ decorator to write a retry Decorator. The following is an implementation example, if you want to write some network services using python, exceptions will always be thrown when the network condition is poor or the resource usage is too high and the task is congested, the current task is terminated. you can use the @ decorator to write a retried decorator. this is a comparison of 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 12 seconds...
The code is as follows:
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
# Tanyewei@gmail.com
#
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)
Failed T 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 ()