Created
August 21, 2020 10:23
-
-
Save simon-engledew/1a2128aea0cac636013c9086bcbec6ad to your computer and use it in GitHub Desktop.
Simple retry mechanism with delay and backoff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"time" | |
"fmt" | |
) | |
func pow(a, b int) int { | |
p := 1 | |
for b > 0 { | |
if b&1 != 0 { | |
p *= a | |
} | |
b >>= 1 | |
a *= a | |
} | |
return p | |
} | |
func pow2(a int) int { | |
return pow(a, 2) | |
} | |
func retry(fn func(int) int) func() int { | |
var attempt int | |
return func() int { | |
time.Sleep(time.Duration(fn(attempt)) * time.Second) | |
attempt++ | |
return attempt | |
} | |
} | |
func main() { | |
for r := retry(pow2); r() <= 3; { | |
fmt.Println("attempt") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment