cron

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2025 License: MIT Imports: 16 Imported by: 0

README

cron manager

Linter Status Go Report Card Go Reference

A robust cron job manager built on robfig/cron with enhanced features for production use.

Key Features

  • Context-aware jobs: func(ctx context.Context) error signature
  • Built-in UI: Web interface for monitoring and control
  • Manual execution: API endpoints for on-demand job runs
  • Middleware support: Extensible pipeline for job processing
  • Enhanced state tracking: Detailed job status monitoring
  • Schedule visualization: Tools for schedule inspection

Middlewares

  • WithLogger Traditional logging via Printf function.
  • WithSLog Logs job execution via slog.
  • WithSentry Reports errors to Sentry (includes panic recovery).
  • WithRecover Recovers from panics (alternative to Sentry).
  • WithDevel Marks development environment in context.
  • WithSkipActive Prevents parallel execution of the same job.
  • WithMaintenance Ensures exclusive execution for maintenance jobs.
  • WithMetrics Tracks execution metrics (count, duration, active jobs).

Built-in UI Preview

Web UI

curl support

Run curl http://localhost:2112/debug/cron for schedule.

cron                   |  schedule     |  next                    |  state
cron=f1                |  * * * * *    |  (starts in 16.505033s)  |  idle
cron=f2                |  * * * * *    |  (starts in 16.505028s)  |  idle
cron=f5                |               |  never                   |  disabled
cron=f3 (maintenance)  |  */2 * * * *  |  (starts in 16.505025s)  |  idle

Run curl -L http://localhost:2112/debug/cron?start=<name> for manual job run.

Run curl -H 'Accept: application/json' http://localhost:2112/debug/cron for json output.

WithMetrics Middleware

  • app_cron_evaluated_total – total processed jobs by state.
  • app_cron_active – active running jobs.
  • app_cron_evaluated_duration_seconds – summary metric with durations.

Example

Please see examples/main.go for basic usage.

    m := cron.NewManager()
    m.Use(
        cron.WithMetrics("test"),
        cron.WithDevel(false),
        cron.WithSLog(sl),
        cron.WithLogger(log.Printf, "test-run"),
        cron.WithMaintenance(log.Printf),
        cron.WithSkipActive(),
        cron.WithRecover(), // recover() inside
        cron.WithSentry(),  // recover() inside
    )
    
    // add simple funcs
    m.AddFunc("f1", "* * * * *", newTask("f1"))
    m.AddFunc("f2", "* * * * *", newTask("f2"))
    m.AddFunc("f5", "", newTask("f5"))
    m.AddMaintenanceFunc("f3", "*/2 * * * *", newTask("f3m"))
    
    // run cron
    if err := m.Run(ctx); err != nil {
        log.Fatal(err)
    }
    
    http.HandleFunc("/debug/cron", m.Handler)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSkipped   = errors.New("skipped")
	ErrNotFound  = errors.New("job not found")
	ErrDuplicate = errors.New("duplicate cron name")
)

Functions

func IsDevelFromContext

func IsDevelFromContext(ctx context.Context) bool

IsDevelFromContext returns isDevel flag from context.

func MaintenanceFromContext

func MaintenanceFromContext(ctx context.Context) bool

func NameFromContext

func NameFromContext(ctx context.Context) string

func NewIsDevelContext

func NewIsDevelContext(ctx context.Context, isDevel bool) context.Context

NewIsDevelContext creates new context with isDevel flag.

func NewMaintenanceContext

func NewMaintenanceContext(ctx context.Context, isMaintenance bool) context.Context

func NewNameContext

func NewNameContext(ctx context.Context, name string) context.Context

Types

type Func

type Func func(ctx context.Context) error

type LogPrintf

type LogPrintf func(format string, v ...interface{})

type Logger

type Logger interface {
	Print(ctx context.Context, msg string, args ...any)
	Error(ctx context.Context, msg string, args ...any)
}

Logger is as simple interface for slog.

type Manager

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

Manager is a Cron manager with context and middleware support.

func NewManager

func NewManager() *Manager

func (*Manager) Add

func (cm *Manager) Add(name string, schedule Schedule, r Runner)

Add adds Runner to cron.

func (*Manager) AddFunc

func (cm *Manager) AddFunc(name string, schedule Schedule, fn Func)

AddFunc adds func to cron.

func (*Manager) AddMaintenanceFunc

func (cm *Manager) AddMaintenanceFunc(name string, schedule Schedule, fn Func)

AddMaintenanceFunc adds func to cron.

func (*Manager) Handler

func (cm *Manager) Handler(w http.ResponseWriter, r *http.Request)

func (*Manager) ManualRun

func (cm *Manager) ManualRun(ctx context.Context, id string) error

ManualRun runs a cron func with middlewares and context.

func (*Manager) Run

func (cm *Manager) Run(ctx context.Context) error

Run is a main function that registers all jobs and starts robfig/cron in separate goroutine.

func (*Manager) State

func (cm *Manager) State() States

State returns job states.

func (*Manager) Stop

func (cm *Manager) Stop() context.Context

Stop stops current cron instance.

func (*Manager) TextSchedule

func (cm *Manager) TextSchedule(w io.Writer)

TextSchedule writes current cron schedule with TabWriter.

func (*Manager) Use

func (cm *Manager) Use(m ...MiddlewareFunc)

Use adds middleware for cron job.

type MiddlewareFunc

type MiddlewareFunc func(Func) Func

func WithDevel

func WithDevel(isDevel bool) MiddlewareFunc

WithDevel sets bool flag to context for detecting development environment.

func WithLogger

func WithLogger(pf LogPrintf, managerName string) MiddlewareFunc

WithLogger logs via Printf function (e.g. log.Printf) all runs.

func WithMaintenance

func WithMaintenance(p LogPrintf) MiddlewareFunc

WithMaintenance puts cron jobs in line, got exclusive lock for maintenance job.

func WithMetrics

func WithMetrics(app string) MiddlewareFunc

WithMetrics tracks total/active/duration metrics for runs.

func WithRecover

func WithRecover() MiddlewareFunc

WithRecover use recover() func. Do not use with WithSentry middleware due to recover() call.

func WithSLog

func WithSLog(lg Logger) MiddlewareFunc

WithSLog logs all runs via slog (see Logger interface).

func WithSentry

func WithSentry() MiddlewareFunc

WithSentry sends all errors to sentry. It's also handles panics.

func WithSkipActive

func WithSkipActive() MiddlewareFunc

WithSkipActive skips funcs if they are already running.

type Runner

type Runner interface {
	Run(context.Context) error
}

type Schedule

type Schedule string

func (Schedule) IsActive

func (ss Schedule) IsActive() bool

func (Schedule) String

func (ss Schedule) String() string

type State

type State struct {
	ID            int
	Name          string
	Schedule      string
	IsMaintenance bool
	LastState     string
	LastErr       error
	LastDuration  time.Duration
	LastUpdatedAt time.Time

	LastRun time.Time
	NextRun time.Time
}

type States

type States []State

func (States) LogValue

func (s States) LogValue() slog.Value

LogValue implements slog.LogValuer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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