# Retry

Package retry is for executing a function repeatedly until it was successful or canceled by the context.

# Source:

# Usage:

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

# Context

Set retry context config, can cancel the retry with context.

Signature:

func Context(ctx context.Context)

Example:

import (
	"context"
	"errors"
	"fmt"
	"github.com/duke-git/lancet/v2/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

Function that retry executes.

Signature:

type RetryFunc func() error

Example:

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

Set times of retry. Default times is 5.

Signature:

func RetryTimes(n uint)

Example:

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

Set duration of retries. Default duration is 3 second.

Signature:

func RetryDuration(d time.Duration)

Example:

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

Executes the retryFunc repeatedly until it was successful or canceled by the context.

Signature:

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

Example:

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
}
Last Updated: 9/29/2022, 1:53:14 PM