golang 重试机机制
一般场景是重试几次后失败
package main
import (
"fmt"
"time"
)
func main() {
retry(func() bool {
return false
}, []int{1, 3, 5})
}
func retry(f func() bool, intervals []int) {
var retryCh = make(chan bool)
start := time.Now()
fmt.Printf("+++++++++ %v, 开始重试 +++++++++++++++++\n", start)
index := 0
for {
go time.AfterFunc(time.Duration(intervals[index])*time.Second, func() {
fmt.Printf("+++++++++ %v: 执行重试 第%d次+++++++++++++++++\n", time.Now(), index+1)
retryCh <- f()
})
if end := time.Now(); <-retryCh {
fmt.Printf("+++++++++%v, 重试成功 total %d Second +++++++++++++++++\n", end, end.Second()-start.Second())
return
}
if end := time.Now(); len(intervals)-1 == index {
fmt.Printf("+++++++++%v, 重试成功 total %d Second +++++++++++++++++\n", end, end.Second()-start.Second())
return
}
index++
}
}
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/16265663.html