go-srvc / mods / tickermod

github.com/go-srvc/mods/tickermod

pkg.go.dev source
go get github.com/go-srvc/mods/tickermod@v1.17.0

README

tickermod

tickermod runs a function on a fixed interval. The ticker stops when the function returns a non-nil error.

package main

import (
	"log/slog"
	"os"
	"time"

	"github.com/go-srvc/mods/logmod"
	"github.com/go-srvc/mods/sigmod"
	"github.com/go-srvc/mods/tickermod"
	"github.com/go-srvc/srvc"
)

func main() {
	srvc.RunAndExit(
		logmod.New(),
		sigmod.New(os.Interrupt),
		tickermod.New(
			tickermod.WithInterval(5*time.Second),
			tickermod.WithFunc(func() error {
				slog.Info("tick")
				return nil
			}),
		),
	)
}

Overview

Package tickermod provides ticker functionality as a module.

Constants

const (
	ErrMissingInterval = errStr("interval not set")
	ErrInvalidInterval = errStr("interval must be positive")
	ErrMissingTickFunc = errStr("tick function not set")
)
const ID = "tickermod"

Types

type Opt

type Opt func(*Ticker) error

func WithFireOnStart

func WithFireOnStart() Opt

WithFireOnStart triggers the tick fn immediately on Run, before the first interval elapses.

func WithFunc

func WithFunc(fn func() error) Opt

WithFunc sets the function to be called on each tick.

func WithFuncCtx

func WithFuncCtx(fn func(context.Context) error) Opt

WithFuncCtx sets a context-aware tick function. The ctx is bound to the ticker's lifecycle and cancelled by Stop.

func WithInterval

func WithInterval(d time.Duration) Opt

WithInterval sets ticker interval.

func WithIntervalFn

func WithIntervalFn(fn func() (time.Duration, error)) Opt

WithIntervalFn sets ticker interval using provided function. The returned duration must be greater than zero.

func WithTickTimeout

func WithTickTimeout(d time.Duration) Opt

WithTickTimeout bounds each individual tick by deriving a per-tick ctx with the supplied timeout. The tick fn must observe the ctx (registered via WithFuncCtx) for the timeout to take effect.

type Ticker

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

func New

func New(opts ...Opt) *Ticker

New creates ticker with given options. WithInterval and WithFunc options are mandatory.

func (*Ticker) ID

func (t *Ticker) ID() string

func (*Ticker) Init

func (t *Ticker) Init() error

func (*Ticker) Run

func (t *Ticker) Run() error

func (*Ticker) Stop

func (t *Ticker) Stop() error

Examples

ExampleNew

package main

import (
	"errors"
	"log/slog"
	"time"

	"github.com/go-srvc/mods/tickermod"
	"github.com/go-srvc/srvc"
)

func main() {
	srvc.RunAndExit(
		tickermod.New(
			tickermod.WithInterval(time.Second),
			tickermod.WithFunc(func() error {
				slog.Info("Hello from ticker")
				return errors.New("ticker error")
			}),
		),
	)
}