ticker

package
v0.0.0-...-1929ff6 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2024 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package ticker provides a dynamic ticker that can change its interval at runtime. The ticker can be stopped gracefully and handles context-based termination.

This package is useful for scenarios where periodic execution of a function is needed and the interval might need to change dynamically based on runtime conditions.

It also invokes a first tick immediately after the ticker starts. It's safe to use it concurrently.

It also terminates gracefully when the context is done (return ctx.Err()) or when the stop signal is received.

Example usage:

ticker := New(time.Second, func(ctx context.Context, t *Ticker) error {
    resp, err := client.GetPrice(ctx)
    if err != nil {
        logger.Err(err).Error().Msg("failed to get price")
        return nil
    }

    observer.SetPrice(resp.GasPrice)
    t.SetInterval(resp.GasPriceInterval)

    return nil
})

err := ticker.Run(ctx)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, interval time.Duration, task Task) error

Run creates and runs a new Ticker.

func SecondsFromUint64

func SecondsFromUint64(d uint64) time.Duration

SecondsFromUint64 converts uint64 to time.Duration in seconds.

Types

type Task

type Task func(ctx context.Context, t *Ticker) error

Task is a function that will be called by the Ticker

type Ticker

type Ticker struct {
	// contains filtered or unexported fields
}

Ticker represents a ticker that will run a function periodically. It also invokes BEFORE ticker starts.

func New

func New(interval time.Duration, runner Task) *Ticker

New creates a new Ticker.

func (*Ticker) Run

func (t *Ticker) Run(ctx context.Context) (err error)

Run runs the ticker by blocking current goroutine. It also invokes BEFORE ticker starts. Stops when (if any): - context is done (returns ctx.Err()) - task returns an error or panics - shutdown signal is received

func (*Ticker) SetInterval

func (t *Ticker) SetInterval(interval time.Duration)

SetInterval updates the interval of the ticker.

func (*Ticker) Stop

func (t *Ticker) Stop()

Stop stops the ticker. Safe to call concurrently or multiple times.

Jump to

Keyboard shortcuts

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