ticker

package
v1.19.4 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package ticker provides a ticker-based runner implementation that executes a function at regular intervals. It combines the github.com/nabbar/golib/runner.Runner interface with error collection capabilities.

The ticker automatically manages goroutine lifecycle, context cancellation, and error collection. It's designed for use cases requiring periodic execution of tasks with proper cleanup and state management.

For more information about the runner package, see github.com/nabbar/golib/runner.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalid = errors.New("invalid instance")

ErrInvalid indicates an operation was attempted on an invalid or nil ticker instance.

Functions

This section is empty.

Types

type Ticker

type Ticker interface {
	libsrv.Runner
	liberr.Errors
}

Ticker is the main interface for ticker-based runners. It combines the Runner interface from github.com/nabbar/golib/runner with error collection capabilities.

The ticker executes a provided function at regular intervals until stopped or until its context is cancelled. All errors returned by the function are collected and can be retrieved via the Errors interface methods.

Thread-safety: All methods are safe for concurrent use.

func New

func New(tick time.Duration, fct func(ctx context.Context, tck *time.Ticker) error) Ticker

New creates a new Ticker instance with the specified tick interval and function.

Parameters:

  • tick: The duration between function executions. If less than 1 millisecond, defaultDuration (30 seconds) will be used instead.
  • fct: The function to execute on each tick. It receives the ticker's context and the underlying *time.Ticker. If nil, a default error-returning function will be used.

The function is executed in a goroutine and receives:

  • ctx: A context that will be cancelled when Stop() is called or the parent context expires
  • tck: The underlying *time.Ticker that can be used for advanced tick control

Returns a Ticker instance that is initially stopped. Call Start() to begin execution.

Example:

tick := ticker.New(5*time.Second, func(ctx context.Context, tck *time.Ticker) error {
    // Perform periodic work
    return doWork(ctx)
})
if err := tick.Start(context.Background()); err != nil {
    log.Fatal(err)
}
defer tick.Stop(context.Background())

Jump to

Keyboard shortcuts

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