repeater

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 26, 2025 License: MIT Imports: 5 Imported by: 1

README

repeater

Simple library for operations repetition in case of errors

Documentation

Go Reference

example
package main

import (
	"flag"
	"fmt"
	"log/slog"
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/Mikhalevich/repeater"
	"github.com/Mikhalevich/repeater/logger"
)

func main() {
	var (
		//nolint:mnd
		count    = flag.Int("c", 3, "repeat count attempts")
		duration = flag.Duration("t", time.Second*1, "wait timeout between failed attempts")
		factor   = flag.Int("f", 0, "factor for exponential timeout backoff")
		jitter   = flag.Bool("j", false, "jitter for exponential timeout backoff")
		log      = slog.New(slog.NewTextHandler(os.Stdout, nil))
	)

	flag.Parse()

	args := flag.Args()
	if len(args) == 0 {
		log.Error("command not specified")
		os.Exit(1)
	}

	var (
		cmd     = args[0]
		cmdArgs = args[1:]
	)

	var out []byte

	if err := repeater.Do(
		func() error {
			var err error

			out, err = exec.Command(cmd, cmdArgs...).Output()
			if err != nil {
				return fmt.Errorf("execute %s: %w", cmd, err)
			}

			return nil
		},
		repeater.WithAttempts(*count),
		repeater.WithTimeout(*duration),
		repeater.WithFactor(*factor),
		repeater.WithJitter(*jitter),
		repeater.WithLogger(logger.NewSLog(log)),
	); err != nil {
		log.Error("unable to run command", slog.String("cmd", strings.Join(args, " ")), slog.String("error", err.Error()))
		os.Exit(1)
	}

	fmt.Fprintln(os.Stdout, string(out))
}

License

Repeater is released under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Do

func Do(doFn func() error, opts ...Option) error

Do executes function while receiving error or attempts were exeded.

Types

type Option

type Option func(opts *options)

Option is a specific option for repeater.

func WithAttempts

func WithAttempts(count int) Option

WithAttempts set max number of attempts in case of failure(3 by default).

func WithFactor

func WithFactor(factor int) Option

WithFactor set factor for exponential backoff timeout calculation(0 by default).

func WithJitter

func WithJitter(enabled bool) Option

WithJitter enable/disable jitter for exponential backoff timeout calculation(false by default).

func WithLogger

func WithLogger(log logger.Logger) Option

WithLogger set custom logger (no logger by default).

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout set a timeout between failure attempts(no timeout by default).

Directories

Path Synopsis
cmd
repeater command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL