github.com/go-srvc/mods/tickermod
go get github.com/go-srvc/mods/tickermod@v1.15.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) errorfunc WithFireOnStart
func WithFireOnStart() OptWithFireOnStart triggers the tick fn immediately on Run, before the first interval elapses.
func WithFunc
func WithFunc(fn func() error) OptWithFunc sets the function to be called on each tick.
func WithFuncCtx
func WithFuncCtx(fn func(context.Context) error) OptWithFuncCtx 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) OptWithInterval sets ticker interval.
func WithIntervalFn
func WithIntervalFn(fn func() (time.Duration, error)) OptWithIntervalFn sets ticker interval using provided function. The returned duration must be greater than zero.
func WithTickTimeout
func WithTickTimeout(d time.Duration) OptWithTickTimeout 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) *TickerNew creates ticker with given options. WithInterval and WithFunc options are mandatory.
func (*Ticker) ID
func (t *Ticker) ID() stringfunc (*Ticker) Init
func (t *Ticker) Init() errorfunc (*Ticker) Run
func (t *Ticker) Run() errorfunc (*Ticker) Stop
func (t *Ticker) Stop() errorExamples
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")
}),
),
)
}