Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python while loop for retries with exponential back offs

I wrote a function that is supposed to try a function several times until this works.

def Retry(attempts,back_off,value):
    for i in range(attempts):
        counter = 0
        while attempts > counter:
            try:
                x = function(value)
            except:
                counter =+ 1
                delay = (counter * back_off) + 1
                print ('trying again in {} seconds'.format(delay))
                sleep(delay)
                continue
            break
        return x

result = Retry(20,2,value)

Each failed attempt should be followed by an exponential growing time break i.e. second attempt after 2 seconds, third attempt after 4 seconds, fourth attempt after 8 seconds and so on. The problem is that in the function I wrote, if the first attempt fails, I just get an infinite series of lines that look like:

trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
....

What am I doing wrong? why the loop is stack there?

like image 514
Blue Moon Avatar asked Feb 01 '26 01:02

Blue Moon


1 Answers

The

counter =+ 1

should be

counter += 1
like image 172
Vikas Ojha Avatar answered Feb 03 '26 10:02

Vikas Ojha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!