Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@dantheman213 dantheman213 commented Aug 11, 2020

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