wait

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: BSD-3-Clause Imports: 3 Imported by: 0

Documentation

Overview

Package wait provides waiting strategies. A Waiter returns a channel that fires when the caller may proceed.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"lesiw.io/wait"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	var (
		start = time.Now()
		since = start
		tries = 0
	)
	fn := func() error {
		tries++
		now := time.Now()
		fmt.Printf("attempt=%d elapsed=%v delay=%v\n",
			tries,
			now.Sub(start).Round(time.Millisecond),
			now.Sub(since).Round(time.Millisecond),
		)
		since = now
		if tries < 5 {
			return fmt.Errorf("bang!")
		}
		return nil
	}
	wtr := wait.Jitter(2 * time.Second)
	for fn() != nil {
		select {
		case <-wtr.Wait():
		case <-ctx.Done():
			return
		}
	}
	fmt.Println("succeeded after", tries, "tries")
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Waiter

type Waiter interface {
	// Wait returns a channel that fires when the caller may proceed.
	Wait() <-chan time.Time
}

Waiter returns a channel that fires after a strategy-determined interval. A Waiter is not safe for concurrent use.

func Decay

func Decay(limit time.Duration) Waiter

Decay returns a waiter whose first five calls are free. The sixth call blocks for limit and the count then resets. The count halves every 2*limit of idle time. Good for supervisor restart loops. Inspired by Suture's failure-decay counter (github.com/thejerf/suture/v4).

func Jitter

func Jitter(limit time.Duration) Waiter

Jitter returns a full-jitter exponential waiter. Successive Wait calls sleep for a random duration in [0, upper), where upper doubles each call starting at limit/1024 and saturating at limit. Default choice for retry pacing across concurrent peers.

Jump to

Keyboard shortcuts

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