Python retry Adorner Sample _python

Source: Internet
Author: User

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.