Skip to content

Instantly share code, notes, and snippets.

@flowck
Forked from dantheman213/exponential_backoff.go
Created December 10, 2022 16:10
Show Gist options
  • Save flowck/75e8a077c89fe5e612a0f5c24fb2aee7 to your computer and use it in GitHub Desktop.
Save flowck/75e8a077c89fe5e612a0f5c24fb2aee7 to your computer and use it in GitHub Desktop.
Golang exponential back off simple example
package main
import "fmt"
import "time"
import "math"
var exponentialBackoffCeilingSecs int64 = 14400 // 4 hours
func main() {
fmt.Println("Hello World")
lastUpdatedAt := time.Now()
attempts := 0
for true {
if time.Now().Sub(lastUpdatedAt).Hours() >= 12 {
attempts = 0
}
lastUpdatedAt = time.Now()
attempts += 1
// exponential back-off implemented
delaySecs := int64(math.Floor((math.Pow(2, float64(attempts)) - 1) * 0.5))
if delaySecs > exponentialBackoffCeilingSecs {
delaySecs = exponentialBackoffCeilingSecs
}
// should only get here if the ffmpeg record stream process dies
fmt.Printf("this is %d attempt to restart. waiting %d seconds and then restarting\n", attempts, delaySecs)
time.Sleep(time.Duration(delaySecs) * time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment