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++
	}
}

posted @ 2022-05-13 10:17  vx_guanchaoguo0  阅读(384)  评论(0编辑  收藏  举报