poll

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package poll provides a Task that periodically executes an action function.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(*options)

Option is an option func for NewTask.

func WithContinueOnError

func WithContinueOnError() Option

WithContinueOnError causes the task to log action errors and continue polling rather than propagating the error and stopping. A logger should be set via WithLogger so errors are visible; without one they are silently discarded.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger used when WithContinueOnError is active and an action returns an error.

func WithRunAtStart

func WithRunAtStart() Option

WithRunAtStart causes the action to execute immediately when Run is called, before the first interval tick.

type Task

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

Task is a task.Task that executes a task.Action on a fixed interval using a ticker. Unlike loop.Task, the interval is clock-based: ticks fire regardless of how long the action takes. If the action takes longer than the interval, the next tick fires immediately after it completes (Go's ticker coalesces missed ticks).

func NewTask

func NewTask(action task.Action, name string, interval time.Duration, opts ...Option) *Task

NewTask creates a new poll Task. action is called on every interval tick. name is used in Name() (returned as "poll: <name>"). Panics if interval is less than or equal to zero. action must return nil when the context is cancelled; a non-nil error either terminates the task (default) or is logged and discarded (WithContinueOnError).

Example

ExampleNewTask demonstrates creating a poll Task that runs an action on a fixed interval, starting immediately.

package main

import (
	"context"
	"log/slog"
	"time"

	"github.com/wood-jp/task/poll"
)

func main() {
	t := poll.NewTask(
		func(ctx context.Context) error {
			// sync state with an external system
			return nil
		},
		"state-syncer",
		30*time.Second,
		poll.WithRunAtStart(),
		poll.WithLogger(slog.Default()),
		poll.WithContinueOnError(),
	)
	_ = t
}

func (*Task) Name

func (t *Task) Name() string

Name returns the name of this task.

func (*Task) Run

func (t *Task) Run(ctx context.Context) error

Run starts the polling loop. It blocks until ctx is cancelled, returning nil, or until the action returns an error (when WithContinueOnError is not set). Returns ErrAlreadyStarted if called more than once.

Jump to

Keyboard shortcuts

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