graceful

package module
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2026 License: MIT Imports: 11 Imported by: 0

README

Graceful

Graceful is a lightweight Go package that provides utilities for managing graceful shutdown of your applications. It offers helper functions to handle OS signals (SIGINT, SIGTERM) and to execute multiple concurrent tasks with proper cancellation support.

Features

  • Signal Handling: Listens for termination signals (SIGINT and SIGTERM) to initiate a graceful shutdown.
  • Concurrent Execution: Leverages Go's errgroup to run multiple tasks concurrently, ensuring clean shutdown and error propagation.

Installation

Use go get to install the package:

go get github.com/LiquidCats/graceful

Usage Example

Below is a simple example that demonstrates how to use the package to run a background task while listening for termination signals:

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/LiquidCats/graceful"
)

func main() {
	ctx := context.Background()

	// Define a runner that performs a periodic task.
	taskRunner := func(ctx context.Context) error {
		for {
			select {
			case <-ctx.Done():
				// Perform any cleanup here
				fmt.Println("TaskRunner shutting down...")
				return ctx.Err()
			default:
				fmt.Println("TaskRunner is running...")
				time.Sleep(2 * time.Second)
			}
		}
	}

	// Wait for either the task to complete or a termination signal.
	err := graceful.WaitContext(ctx, taskRunner, graceful.Signals)
	if err != nil {
		fmt.Println("Exited with error:", err)
	}

	fmt.Println("Exited gracefully.")
}

How It Works

  • Signals Function:

    • Creates a channel to receive OS signals (SIGINT, SIGTERM).
    • Returns when one of the signals is received, initiating shutdown.
  • WaitContext Function:

    • Accepts a context and one or more runner functions (each with the signature func(context.Context) error).
    • Runs each runner concurrently using an errgroup.
    • Cancels the context if any runner returns an error or if a termination signal is received.

Contributing

Contributions are welcome! Feel free to open issues or submit pull requests for bug fixes, improvements, or new features.

License

Distributed under the MIT License. See LICENSE for more information.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrShutdownBySignal = eris.New("shutdown by signal")
View Source
var ErrTickerFailure = eris.New("ticker failure")
View Source
var ErrWorkerFailure = eris.New("worker failure")

Functions

func Signals

func Signals(ctx context.Context) error

func WaitContext

func WaitContext(ctx context.Context, runners ...Runner) error

Types

type Runner

type Runner func(ctx context.Context) error

func ScheduleRunner

func ScheduleRunner(tasks ...Task) Runner

func Server

func Server(router http.Handler, opts ...ServerOpt) Runner

func Ticker added in v2.0.1

func Ticker(interval time.Duration, runner Runner, opts ...TickerOpt) Runner

func Worker

func Worker[T any](ch <-chan T, runner WorkerHandler[T], opts ...WorkerOpt) Runner

type ServerOpt

type ServerOpt func(*server)

func WithPort

func WithPort(port string) ServerOpt

func WithReadTimeout

func WithReadTimeout(timeout time.Duration) ServerOpt

func WithWriteTimeout

func WithWriteTimeout(timeout time.Duration) ServerOpt

type Task

type Task interface {
	Spec() string
	Run()
}

type TickerOpt

type TickerOpt func(*ticker)

func WithTickerLogger

func WithTickerLogger(logger *zerolog.Logger) TickerOpt

type WorkerHandler

type WorkerHandler[T any] func(context.Context, T) error

type WorkerOpt

type WorkerOpt func(*worker)

func WithWorkerLogger

func WithWorkerLogger(logger *zerolog.Logger) WorkerOpt

Jump to

Keyboard shortcuts

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