# Retry

retry 重试执行函数直到函数运行成功或被 context cancel。

# 源码:

# 用法:

import (
    "github.com/duke-git/lancet/v2/retry"
)

# Document 文档

# Context

设置重试context参数

函数签名:

func Context(ctx context.Context)

例子:

import (
	"context"
	"errors"
	"fmt"
	"lancet-demo/retry"
	"time"
)

func main() {
	ctx, cancel := context.WithCancel(context.TODO())
	var number int
	increaseNumber := func() error {
		number++
		if number > 3 {
			cancel()
		}
		return errors.New("error occurs")
	}

	err := retry.Retry(increaseNumber,
		retry.RetryDuration(time.Microsecond*50),
		retry.Context(ctx),
	)

	if err != nil {
		fmt.Println(err) //retry is cancelled
	}
}

# RetryFunc

被重试执行的函数

函数签名:

type RetryFunc func() error

例子:

package main

import (
    "fmt"
    "errors"
    "log"
    "github.com/duke-git/lancet/v2/retry"
)

func main() {
    var number int
	increaseNumber := func() error {
		number++
		if number == 3 {
			return nil
		}
		return errors.New("error occurs")
	}

	err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50))
    if err != nil {
		log.Fatal(err)
	}

    fmt.Println(number) //3
}

# RetryTimes

设置重试次数,默认5

函数签名:

func RetryTimes(n uint)

例子:

package main

import (
    "fmt"
    "errors"
    "log"
    "github.com/duke-git/lancet/v2/retry"
)

func main() {
    var number int
	increaseNumber := func() error {
		number++
		if number == 3 {
			return nil
		}
		return errors.New("error occurs")
	}

	err := retry.Retry(increaseNumber, retry.RetryTimes(2))
    if err != nil {
		log.Fatal(err) //2022/02/01 18:42:25 function main.main.func1 run failed after 2 times retry exit status 1
	}
}

# RetryDuration

设置重试间隔时间,默认3秒

函数签名:

func RetryDuration(d time.Duration)

例子:

package main

import (
    "fmt"
    "errors"
    "log"
    "github.com/duke-git/lancet/v2/retry"
)

func main() {
    var number int
	increaseNumber := func() error {
		number++
		if number == 3 {
			return nil
		}
		return errors.New("error occurs")
	}

	err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50))
    if err != nil {
		log.Fatal(err)
	}

    fmt.Println(number) //3
}

# Retry

重试执行函数retryFunc,直到函数运行成功,或被context停止

函数签名:

func Retry(retryFunc RetryFunc, opts ...Option) error

例子:

package main

import (
    "fmt"
    "errors"
    "log"
    "github.com/duke-git/lancet/v2/retry"
)

func main() {
    var number int
	increaseNumber := func() error {
		number++
		if number == 3 {
			return nil
		}
		return errors.New("error occurs")
	}

	err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50))
    if err != nil {
		log.Fatal(err)
	}

    fmt.Println(number) //3
}
最后更新时间: 2022/9/29 下午1:53:14