Skip to content

Instantly share code, notes, and snippets.

@simon-engledew
Created August 21, 2020 10:23
Show Gist options
  • Save simon-engledew/1a2128aea0cac636013c9086bcbec6ad to your computer and use it in GitHub Desktop.
Save simon-engledew/1a2128aea0cac636013c9086bcbec6ad to your computer and use it in GitHub Desktop.
Simple retry mechanism with delay and backoff
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