Skip to content

Instantly share code, notes, and snippets.

@dantheman213
Last active December 10, 2022 16:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dantheman213/db6aa0c4d2071aed359b15c8d98d01b4 to your computer and use it in GitHub Desktop.
Save dantheman213/db6aa0c4d2071aed359b15c8d98d01b4 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)
}
}
@dantheman213
Copy link
Author

Hello World
this is 1 attempt to restart. waiting 0 seconds and then restarting
this is 2 attempt to restart. waiting 1 seconds and then restarting
this is 3 attempt to restart. waiting 3 seconds and then restarting
this is 4 attempt to restart. waiting 7 seconds and then restarting
this is 5 attempt to restart. waiting 15 seconds and then restarting
this is 6 attempt to restart. waiting 31 seconds and then restarting
this is 7 attempt to restart. waiting 63 seconds and then restarting
this is 8 attempt to restart. waiting 127 seconds and then restarting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment