worker

package
v1.67.2 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 3 Imported by: 0

README

Package worker

Пакет worker предоставляет настраиваемый воркер для периодического запуска задач с контролем параллелизма и возможностью корректного завершения.

Types

Job

Интерфейс задачи, которую выполняет воркер.

Methods:

Do(ctx context.Context)

Выполнить задачу.

Worker

Структура воркера, выполняющего задачу с заданным интервалом и уровнем параллелизма.

Fields:

interval time.Duration

Интервал между запусками задачи (по умолчанию 1 секунда).

concurrency int

Количество параллельных воркеров (по умолчанию 1).

Methods:

New(job Job, opts ...Option) *Worker

Создаёт воркера с опциями и задачей для выполнения.

Run(ctx context.Context)

Запускает воркер(ы). Операция неблокирующая.

Shutdown()

Останавливает все воркеры и ожидает их завершения.

Опции для конфигурации воркера:

WithInterval(interval time.Duration) Option

Установить интервал между запусками.

WithConcurrency(concurrency int) Option

Установить количество параллельных воркеров.

Usage

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/txix-open/worker"
)

// Пример задачи
type PrintJob struct{}

func (p PrintJob) Do(ctx context.Context) {
	fmt.Println("Job executed at", time.Now())
}

func main() {
	job := PrintJob{}

	// Создаём воркер с интервалом 2 секунды и 3 параллельными воркерами
	w := worker.New(job,
		worker.WithInterval(2*time.Second),
		worker.WithConcurrency(3),
	)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Запускаем воркер
	w.Run(ctx)

	// Работаем 7 секунд
	time.Sleep(7 * time.Second)

	// Останавливаем воркеры и ждём завершения
	w.Shutdown()

	fmt.Println("Worker shutdown complete")
}

Documentation

Overview

Package worker provides a configurable worker for periodic task execution with concurrency control and graceful shutdown support.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Job

type Job interface {
	// Do executes the task.
	Do(ctx context.Context)
}

Job is an interface for tasks executed by the worker.

type Option

type Option func(w *Worker)

Option is a function type that configures a Worker.

func WithConcurrency

func WithConcurrency(concurrency int) Option

WithConcurrency sets the number of parallel workers. The default concurrency is 1 if not specified.

Example:

w := worker.New(myJob, worker.WithConcurrency(3))

func WithInterval

func WithInterval(interval time.Duration) Option

WithInterval sets the time interval between job executions. The default interval is 1 second if not specified.

Example:

w := worker.New(myJob, worker.WithInterval(5*time.Second))

type Worker

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

Worker manages periodic execution of a Job with configurable concurrency.

func New

func New(job Job, opts ...Option) *Worker

New creates a new Worker with the specified Job and options. Default configuration: interval of 1 second and concurrency of 1.

Example:

w := worker.New(myJob, worker.WithInterval(2*time.Second), worker.WithConcurrency(3))

func (*Worker) Run

func (w *Worker) Run(ctx context.Context)

Run starts the worker goroutines. The operation is non-blocking. Each worker runs independently and processes jobs according to the configured interval.

The context parameter controls the lifecycle of the workers. When the context is cancelled, workers will complete their current job and exit.

func (*Worker) Shutdown

func (w *Worker) Shutdown()

Shutdown stops all workers and waits for them to complete. This method blocks until all goroutines have finished.

Shutdown is safe for concurrent use.

Jump to

Keyboard shortcuts

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