Go gadget series — retrial mechanism

Time:2021-4-19

Requirement: if we want a code to be retried several times in case of execution failure and then throw an error, how to implement it in go?

//Retrying, limit times
func Retry(tryTimes int, sleep time.Duration, callback func() (map[string]interface{}, error)) map[string]interface{} {
    for i := 1; i <= tryTimes; i++ {
        ret, err := callback()
        if err == nil {
            return ret
        }
        if i == tryTimes {
            panic(fmt.Sprintf("error info: %s", err.Error()))
            return nil
        }
        time.Sleep(sleep)
    }
    return nil
}

use

//The maximum number of retries is 3, with an interval of 1 second
Retry(3, 1*time.Second, obj.Run)

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Envoy announced alpha version of native support for windows

Author: sunjay Bhatia Since 2016, porting envoy to the windows platform has been an important part of the projectOne of the goalsToday, we are excited to announce the alpha version of envoy’s windows native support. The contributor community has been working hard to bring the rich features of envoy to windows, which is another step […]