loop

package
v1.0.0 Latest Latest
Warning

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

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

Documentation

Overview

Package loop provides a Task that repeatedly 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 looping 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 WithDelay

func WithDelay(d time.Duration) Option

WithDelay sets a context-aware sleep between runs (default: 0, no sleep). The delay occurs after each run completes before the next begins. Use WithInitialDelay to also sleep before the first run.

func WithInitialDelay

func WithInitialDelay() Option

WithInitialDelay causes the delay (set via WithDelay) to also apply before the first run.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger to be used for per-run log lines.

type Task

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

Task is a task.Task that calls a task.Action in a loop until the context is cancelled or the action returns an error. If the action returns nil, it is called again (after an optional delay).

func NewTask

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

NewTask creates a new loop Task. action is called on each iteration. name is used in Name() (returned as "loop: <name>") and in log output.

Example

ExampleNewTask demonstrates creating a loop Task that retries an action continuously with a delay between runs.

package main

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

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

func main() {
	t := loop.NewTask(
		func(ctx context.Context) error {
			// perform a unit of work
			return nil
		},
		"my-worker",
		loop.WithDelay(5*time.Second),
		loop.WithLogger(slog.Default()),
		loop.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 loops forever: call action, repeat. Exits without error when ctx is cancelled. Propagates any action error (unless WithContinueOnError is set). Returns task.ErrAlreadyStarted if called more than once.

Jump to

Keyboard shortcuts

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