cron

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

grpcproc/cron

Jobs on crontab schedules for grpcproc, in a process the application starts. Each run is a process of its own, so a run's exit reason is its result, an overlapping run can be skipped or replaced, and a slow one is told to exit. A package of grpcproc's, built on its public API alone.

go get github.com/floatdrop/grpcproc # cron is a package of the core module
c, err := cron.Start(node, cron.Spec{Jobs: []cron.Job{{
    Name:     "nightly-report",
    Spec:     "10 3 * * *",
    Location: berlin, // UTC if nil
    Action:   cron.Call(reporter, func(r cron.Run) *reportpb.Make { return &reportpb.Make{Day: r.Time.Format(time.DateOnly)} }),
    Overlap:  cron.Forbid,
    Timeout:  10 * time.Minute,
    OnFailure: func(r cron.Run, reason string) { alerts.Page("report", reason) },
}}}, grpcproc.WithName("cron"))

// or under a supervisor
child, err := cron.Child("cron", spec)

Schedules

Five fields: minute, hour, day of month, month, day of week. Each is * or a list of values, ranges and steps (0,30, 9-17, */15, 0-30/10, 5/20). Months and weekdays take names (JAN, mon-fri); Sunday is 0 or 7. When both day fields are restricted a day matching either runs; when one starts with * a day must match both, as in Vixie cron.

Extension Field Means
L day of month the month's last day
5L day of week the month's last Friday
5#2 day of week the month's second Friday
@hourly, @daily (@midnight), @weekly, @monthly, @yearly (@annually) whole spec 0 * * * *, 0 0 * * *, 0 0 * * 0, 0 0 1 * *, 0 0 1 1 *

cron.Parse(spec) returns the Schedule, whose Next(t) is the first minute after t it names, in t's zone: a preview of when a job runs.

Time zones and clock changes

A job's Spec is read in its Location, UTC when nil, so every node reads it alike. A minute that clocks skip when they go forward does not exist, and a job due then does not run that day. A minute they repeat when they go back runs the first time only: 30 1 * * * in New York runs at 01:30 EDT on November 1, not again at 01:30 EST. Next gives the same answers, so it previews exactly what runs.

The process checks the time at the start of every minute, by the wall clock: a clock stepped back does not run a minute twice, and one stepped forward skips minutes as a stopped process would.

Runs

Each run is a process spawned by the cron process, linked to it (it ends if the cron process does), labelled cron:<job>. Its Action is one of:

Action The run
cron.Send(to, build) sends build(run) to to, and succeeds once sent
cron.Call(to, build) calls to, on this node or another, and succeeds if the answer is not an error
cron.Func(fn) runs fn(ctx, run); ctx ends when the run is told to exit
any func(*grpcproc.Process[proto.Message], cron.Run) error is that process

Run.Time is the minute the run was due, in the job's zone.

A run fails with any exit reason but normal: the error it returned, a panic, timeout or replaced. OnFailure hears of it on the cron process's goroutine (it must not block), and the process logs it and publishes it through its inspect map, so grpcprocctl inspect shows every job, when it runs next and last ran, how many runs are going and why the last one failed.

Overlap A run due while the job's previous run still goes
Allow (default) starts beside it
Forbid is skipped
Replace starts, once the previous one is told to exit with replaced

Missed runs

A run is due at the start of its minute. One missed while the cron process was not running, or was held up, is skipped, unless the job has a StartingDeadline: then the latest run it missed starts late, once, if it is still within the deadline. The process reports its *cronv1.State, each job's last run, through Spec.OnState whenever a run starts, and a process started with it as Spec.Resume catches up from there. It checks the minute it starts in at once: a run due in it that the process it takes over from did not start, starts then. A supervisor that restarts a cron process resumes it from its last state by itself.

That is how a job runs once in a cluster: a grpcproc/leader singleton runs the cron process on the leader, checkpoints its state, and the next leader resumes from it.

leader.Start(node, leader.Spec[*cronv1.State]{
    Cluster: "cron",
    Voters:  []string{"a", "b", "c"},
    Singleton: func(l *leader.Lease[*cronv1.State], last *cronv1.State) (actor.ChildSpec, error) {
        return cron.Child("cron", cron.Spec{Jobs: jobs, Resume: last, OnState: l.Save})
    },
})

Changing jobs

c.AddJob(ctx, node, job)            // only from c's node: a job holds Go functions
c.DisableJob(ctx, node, "nightly")  // from any node
c.EnableJob(ctx, node, "nightly")   // runs from the next minute; nothing missed is caught up
c.RemoveJob(ctx, node, "nightly")

c = cron.Named("a", "cron")         // a cron process by its name

c is a cron.Crontab, what cron.Start returns. Each change takes who asks, the node or a process from inside its handler, as an address's Call does.

Runs already going go on. A cron process a supervisor restarts starts again from its Spec's jobs.

From a terminal, grpcprocctl cron lists every cron process of the cluster and its jobs, and enables, disables or removes one; an AI agent gets the same as MCP tools.

Documentation

Overview

Package cron runs jobs on schedules written in crontab syntax, from a grpcproc process the application starts:

c, err := cron.Start(node, cron.Spec{Jobs: []cron.Job{{
	Name:     "nightly-report",
	Spec:     "10 3 * * *",
	Location: berlin,
	Action:   cron.Send(reporter, func(r cron.Run) *reportpb.Make { return &reportpb.Make{Day: r.Time.Format(time.DateOnly)} }),
}}}, grpcproc.WithName("cron"))

The process checks the time at the start of every minute, and starts the jobs due then. Every run is a process of its own, linked to the cron process, so a run that fails is its exit reason, one that is still going when the next is due can be left alone, skipped or replaced (Overlap), one that takes too long is told to exit (Timeout), and every run shows up among the node's processes, labelled "cron:" and its job's name.

A job's Spec is read in its own Location, UTC unless set. A minute that clocks skip when they go forward does not exist, so nothing due then runs; one they repeat when they go back runs the first time only.

Only this node's jobs are its: every node that starts a cron process runs its jobs. For a job that runs once in the cluster, run the cron process as a grpcproc/leader singleton, which resumes on the next leader from the State the last one reported.

Index

Examples

Constants

View Source
const (
	ReasonTimeout  = "timeout"
	ReasonReplaced = "replaced"
)

The exit reasons the cron process gives the runs it tells to exit.

Variables

View Source
var (
	// ErrNoJob is the answer to a change to a job the cron process does
	// not have.
	ErrNoJob = errors.New("cron: no such job")
	// ErrJobExists is the answer to AddJob with a name the cron process
	// already has.
	ErrJobExists = errors.New("cron: a job has that name")
)

Functions

func Child

func Child(name string, spec Spec, opts ...grpcproc.SpawnOption) (actor.ChildSpec, error)

Child checks spec and returns a child for a supervisor, registered as name unless name is empty, that runs a cron process for it.

Types

type Action

type Action func(p *grpcproc.Process[proto.Message], r Run) error

Action is what a run does, in a process of its own spawned by the cron process and linked to it: its return is the run's exit reason. A run told to exit (Overlap Replace, Timeout, or the cron process ending) has its context cancelled. A run that returns context.DeadlineExceeded once its Deadline has passed ends with reason "timeout", as one told to exit at its Deadline does.

func Call

func Call[N proto.Message](to grpcproc.Addr[N], req func(Run) N) Action

Call is an Action that calls to with what req builds for the run. The run succeeds when to answers without an error, and fails with the error otherwise; the job's Timeout bounds the wait, and to sees the run's Deadline as the call's.

func Func

func Func(fn func(ctx context.Context, r Run) error) Action

Func is an Action that calls fn with the run's context, which ends at the run's Deadline.

func Send

func Send[N proto.Message](to grpcproc.Addr[N], msg func(Run) N) Action

Send is an Action that sends what msg builds for the run to to. The run succeeds once the message is sent: what its receiver makes of it is the receiver's. A first send to a node with no link yet waits for the dial within the run's Deadline.

type Crontab

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

Crontab addresses a cron process, and changes its jobs: what Start returns, or Named finds. from, in each of its methods, is who asks: the Node, or a Process from inside its handler, as for grpcproc.Addr.Call.

func Named

func Named(node, name string) Crontab

Named addresses the cron process registered as name on node.

func Start

func Start(n *grpcproc.Node, spec Spec, opts ...grpcproc.SpawnOption) (Crontab, error)

Start checks spec and spawns a cron process for it on n, and returns its Crontab. opts apply to the process: a name, to reach it by.

func (Crontab) AddJob

func (c Crontab) AddJob(ctx context.Context, from grpcproc.Caller, job Job) error

AddJob adds job to the cron process. from must be on its node: a job holds Go functions, which no message can carry, and the cron process refuses a caller of another node. The job's runs are due from the minute after it is added.

func (Crontab) Addr

func (c Crontab) Addr() grpcproc.Addr[*cronv1.Control]

Addr returns the address of the cron process, to monitor it, link to it, or ask it to exit.

func (Crontab) DisableJob

func (c Crontab) DisableJob(ctx context.Context, from grpcproc.Caller, name string) error

DisableJob keeps a job but runs it no more until EnableJob. Its runs already going go on.

func (Crontab) EnableJob

func (c Crontab) EnableJob(ctx context.Context, from grpcproc.Caller, name string) error

EnableJob runs a disabled job again, from the minute after. Runs it missed while disabled are not caught up.

func (Crontab) RemoveJob

func (c Crontab) RemoveJob(ctx context.Context, from grpcproc.Caller, name string) error

RemoveJob removes the job called name, from any node. Its runs already going go on.

func (Crontab) String

func (c Crontab) String() string

type Job

type Job struct {
	// Name identifies the job in its cron process.
	Name string
	// Spec is when the job runs, in crontab syntax: see Parse.
	Spec string
	// Location is the time zone Spec is read in. Nil means UTC, so that
	// the nodes of a cluster read a spec alike whatever their own zone.
	Location *time.Location
	// Action is what a run does.
	Action Action
	// Overlap says what happens when a run is due while the job's previous
	// run still goes. By default, Allow.
	Overlap Overlap
	// Timeout, if positive, bounds a run: one that outlives it is told to
	// exit, with reason "timeout".
	Timeout time.Duration
	// StartingDeadline, if positive, is how late a run may start. A run
	// missed while the cron process was not running (a node restarted, a
	// leader changed) or was held up starts late if it is still within
	// the deadline, once however many of the job's runs were missed. By
	// default a missed run is skipped.
	StartingDeadline time.Duration
	// Disabled keeps the job without running it, until EnableJob.
	Disabled bool
	// OnFailure, if set, is told of every run that ends with a reason
	// other than normal: the error its Action returned, a panic, "timeout"
	// or "replaced". It runs on the cron process's goroutine, so it must not
	// block.
	OnFailure func(r Run, reason string)
}

Job is a task run on a schedule.

type Overlap

type Overlap uint8

Overlap says what a job does when a run is due while its previous run still goes.

const (
	// Allow starts the run beside the previous one.
	Allow Overlap = iota
	// Forbid skips the run: the previous one goes on.
	Forbid
	// Replace tells the previous run to exit, with reason "replaced", and
	// starts the new one.
	Replace
)

func (Overlap) String

func (o Overlap) String() string

type Run

type Run struct {
	Job string
	// Time is the minute the run was due, in its job's Location. A run
	// that starts late, within its job's StartingDeadline, keeps it.
	Time time.Time
	// Deadline is when the run is told to exit, from its job's Timeout:
	// zero for a job with none.
	Deadline time.Time
}

Run is one run of a job, as its Action sees it.

type Schedule

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

Schedule is a parsed crontab spec: the minutes it names, in whatever location it is asked about.

func Parse

func Parse(spec string) (*Schedule, error)

Parse reads a crontab spec: five fields, minute (0-59), hour (0-23), day of month (1-31), month (1-12 or JAN-DEC) and day of week (0-7 or SUN-SAT, Sunday being 0 and 7). A field is * or a comma-separated list of values, ranges (1-5) and steps (*/15, 0-30/10, 5/20, which is 5-59/20). When both day fields are restricted a day matching either runs, and when either starts with * a day must match both, as in Vixie cron.

Beyond the standard, as in Quartz: L in the day of month is its last day; in the day of week, 5L is the month's last Friday and 5#2 its second. The macros are @yearly (or @annually), @monthly, @weekly, @daily (or @midnight) and @hourly; @reboot is not a schedule.

func (*Schedule) Next

func (s *Schedule) Next(t time.Time) time.Time

Next is the first minute after t that s names, in t's location, or the zero time if there is none within the next ten years (as for "0 0 30 2 *"). A minute that is skipped when clocks go forward does not exist, so it never matches; one that repeats when clocks go back matches the first time only.

Example
package main

import (
	"fmt"
	"time"

	"github.com/floatdrop/grpcproc/cron"
)

func main() {
	s, err := cron.Parse("30 1 * * *")
	if err != nil {
		panic(err)
	}
	// On November 1, 2026, New York's clocks go back from 02:00 to 01:00:
	// 01:30 comes twice, and the job runs the first time.
	ny, _ := time.LoadLocation("America/New_York")
	t := time.Date(2026, 10, 31, 12, 0, 0, 0, ny)
	for range 3 {
		t = s.Next(t)
		fmt.Println(t.Format("Mon Jan 2 15:04 MST"))
	}
}
Output:
Sun Nov 1 01:30 EDT
Mon Nov 2 01:30 EST
Tue Nov 3 01:30 EST

func (*Schedule) String

func (s *Schedule) String() string

String is the spec s was parsed from.

type Spec

type Spec struct {
	// Jobs run from the start of the minute after the process starts.
	Jobs []Job
	// Resume is the State an earlier cron process reported through
	// OnState: each job's last run, from which a job with a
	// StartingDeadline catches up on what it missed since.
	Resume *cronv1.State
	// OnState, if set, is given the process's State every time a job
	// starts a run. It runs on the cron process's goroutine, so it must
	// not block. A cron process that a supervisor restarts resumes from the
	// last State it reported, whether OnState is set or not.
	OnState func(*cronv1.State)
}

Spec describes a cron process.

Directories

Path Synopsis
proto

Jump to

Keyboard shortcuts

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