cronfab

package module
v0.0.0-...-c65567f Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2021 License: MIT Imports: 9 Imported by: 0

README

Cronfab

Cronfab is a crontab time-and-date specification parser and processor with a configurable calendar.

All the unix standard features are supported:

  • units may be specified by number or name
  • lists and ranges are suppored
  • step values are supported

Cronfab does not support shell command execution, or specification nicknames (such as @reboot, @annually, @yearly, @monthly, @weekly, @daily or @hourly).

Parsers for classic 6-field (year, month, day of month, day of week, hour of day, minute or hour) and extended, 8 field, (6-field version extended to second of minute and week of month) are provided. Other calendars and/or periods may be added.

Examples and Tests are the best source of documentation.

Example

The example below outputs the parsed crontab entry and then runs for 20s, producing output every 5s. The example demonstrates generating timeseries for a parsed crontab.

// crontab event at every 5 second interval
func ExampleEveryFiveSeconds() {
	markers, err := cronfab.SecondContabConfig.ParseCronTab("*/5 * * * * * *")
	if err != nil {
		fmt.Printf("err: %v\n", err)
	}
	fmt.Printf("%v\n", markers)

	// run for 4 intervals
	for i := 0; i < 4; i++ {
		t1, err := cronfab.SecondContabConfig.Next(markers, time.Now())
		if err != nil {
			fmt.Printf("err: %v\n", err)
			return
		}
		dt := t1.Sub(time.Now())
		time.Sleep(dt)
		fmt.Fprintf(os.Stderr, "time: %v\n", time.Now())
	}

	// Output: 0-59/5 0-59/1 0-23/1 1-31/1 1-5/1 1-12/1 0-6/1
}

Documentation

Index

Examples

Constants

View Source
const (
	StateExpectSplatOrNumberOrName = State(iota)
	StateInNumber                  // next must be '0'-'9' or ',' or ' ' or '-'
	StateInName                    // next must be 'a'-'z' or ',' or ' ' or '-'
	StateExpectEndRangeNumber      // next must be '0'-'9'
	StateInEndRangeNumber          // next must be '0'-'9' or '/' or ',' or ' '
	StateExpectEndRangeName        // next must be '0'-'9'
	StateInEndRangeName            // next must be 'a'-'z' or '/' or ',' or ' '
	StateExpectStep                // next must be '/' or ',' or ' '
	StateExpectStepNumber          // next must be '0'-'9'
	StateInStepNumber              // next must be '0'-'9' or ',' or ' '
)

Variables

View Source
var DefaultContabConfig = NewCrontabConfig([]FieldConfig{
	{
		unit: MinuteUnit{},
		name: "minute",
		min:  0,
		max:  59,
		getIndex: func(t time.Time) int {
			return t.Minute()
		},
	},
	{
		unit: HourUnit{},
		name: "hour",
		min:  0,
		max:  23,
		getIndex: func(t time.Time) int {
			return t.Hour()
		},
	},
	{
		unit: DayUnit{},
		name: "day of month",
		min:  1,
		max:  31,
		getIndex: func(t time.Time) int {
			return t.Day()
		},
	},
	{
		unit:       MonthUnit{},
		name:       "month",
		rangeNames: []string{"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"},
		min:        1,
		max:        12,
		getIndex: func(t time.Time) int {
			return int(t.Month())
		},
	},
	{
		unit:       DayUnit{},
		name:       "day of week",
		rangeNames: []string{"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"},
		min:        0,
		max:        6,
		getIndex: func(t time.Time) int {
			return int(t.Weekday())
		},
	},
})
View Source
var (
	ErrConstraintBoundariesReversed = errors.New("constraint boundaries reversed")
)
View Source
var (
	ErrMaxit = errors.New("maximum number of iterations met")
)
View Source
var (
	ErrOverlappingConstraint = errors.New("overlapping constraint")
)
View Source
var (
	MaxIt = 20000
)
View Source
var SecondContabConfig = NewCrontabConfig([]FieldConfig{
	{
		unit: SecondUnit{},
		name: "second",
		min:  0,
		max:  59,
		getIndex: func(t time.Time) int {
			return t.Second()
		},
	},
	{
		unit: MinuteUnit{},
		name: "minute",
		min:  0,
		max:  59,
		getIndex: func(t time.Time) int {
			return t.Minute()
		},
	},
	{
		unit: HourUnit{},
		name: "hour",
		min:  0,
		max:  23,
		getIndex: func(t time.Time) int {
			return t.Hour()
		},
	},
	{
		unit: DayUnit{},
		name: "day of month",
		min:  1,
		max:  31,
		getIndex: func(t time.Time) int {
			return t.Day()
		},
	},
	{
		unit: WeekOfMonth{},
		name: "week of month",
		min:  1,
		max:  5,
		getIndex: func(t time.Time) int {
			q := t.Day() + (6 - int(t.Weekday()))
			return (q / 7) + 1
		},
	},
	{
		unit:       MonthUnit{},
		name:       "month",
		rangeNames: []string{"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"},
		min:        1,
		max:        12,
		getIndex: func(t time.Time) int {
			return int(t.Month())
		},
	},
	{
		unit:       DayUnit{},
		name:       "day of week",
		rangeNames: []string{"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"},
		min:        0,
		max:        6,
		getIndex: func(t time.Time) int {
			return int(t.Weekday())
		},
	},
})

Functions

func SortUnits

func SortUnits(us []Unit)

func StateString

func StateString(x State) string

StateString returns a human readable string for the parser state. Used in error messages

Types

type CrontabConfig

type CrontabConfig struct {
	Fields     []FieldConfig
	FieldUnits map[string][]int
	Units      []Unit
}

CrontabConfig models the possible time specifications for a crontab entry

func NewCrontabConfig

func NewCrontabConfig(fields []FieldConfig) *CrontabConfig

NewCrontabConfig return a new crontab config for the supplied filed configs

func (CrontabConfig) Len

func (cc CrontabConfig) Len() int

Len crontab config is sortable

func (*CrontabConfig) NameToNumber

func (cc *CrontabConfig) NameToNumber(i int, s string) int

NameToNumber convert a constraint mnemonic to an index

func (*CrontabConfig) Next

func (cc *CrontabConfig) Next(ctl CrontabLine, n time.Time) (time.Time, error)

Next return the next time after n as specified in the CrontabLine

func (*CrontabConfig) ParseCronTab

func (cc *CrontabConfig) ParseCronTab(s string) (CrontabLine, error)

ParseCronTab parses a crontab string using the crontab configuration

func (*CrontabConfig) SetGroupName

func (cc *CrontabConfig) SetGroupName(state State, i, fieldi int, a *CrontabConstraint, s string) error

SetGroupName convert the group member name to an index for field fieldi

func (*CrontabConfig) SetGroupNumber

func (cc *CrontabConfig) SetGroupNumber(state State, i, fieldi int, a *CrontabConstraint, s string) error

SetGroupNumber convert the group member number to an index for field fieldi

type CrontabConstraint

type CrontabConstraint [3]int

CrontabConstraint a crontab constraint expressed as {min, max, step}.

func (CrontabConstraint) Ceil

func (cc CrontabConstraint) Ceil(x int) (int, bool)

Ceil return the current or next greater value that satisfies the constraint.

func (CrontabConstraint) GetMax

func (cc CrontabConstraint) GetMax() int

GetMax get the maximum value of the range

func (CrontabConstraint) GetMin

func (cc CrontabConstraint) GetMin() int

GetMin get the minimum value of the range

func (CrontabConstraint) GetStep

func (cc CrontabConstraint) GetStep() int

GetStep get the step value for the range. 1 if no step was specified.

func (CrontabConstraint) String

func (cc CrontabConstraint) String() string

func (CrontabConstraint) Validate

func (cc CrontabConstraint) Validate() error

Validate return an error if the constraint boundaries are invalid

type CrontabField

type CrontabField [][3]int

CrontabField a crontab field which is an array of constraints

func (CrontabField) Ceil

func (cf CrontabField) Ceil(x int) (int, bool)

func (CrontabField) GetConstraint

func (cf CrontabField) GetConstraint(i int) CrontabConstraint

GetConstraint return constraint at i

func (CrontabField) Len

func (cf CrontabField) Len() int

Len return the number of constraints

func (*CrontabField) SetConstraint

func (cf *CrontabField) SetConstraint(i int, c CrontabConstraint)

SetConstraint set the constraint at i

func (CrontabField) Sort

func (cf CrontabField) Sort()

Sort sort the crontab constrains chronologically

func (CrontabField) String

func (cf CrontabField) String() string

func (CrontabField) Validate

func (cf CrontabField) Validate() error

Validate the constraints for overlap

type CrontabLine

type CrontabLine [][][3]int

CrontabLine represents the parsed user supplied contab specification

func (CrontabLine) GetField

func (cl CrontabLine) GetField(i int) CrontabField

GetField return the crontab field at index i

func (*CrontabLine) SetConstraint

func (cl *CrontabLine) SetConstraint(i int, j int, c CrontabConstraint)

SetConstraint set the field constraint for crontab field i, constraint j

func (*CrontabLine) SetField

func (cl *CrontabLine) SetField(i int, f CrontabField)

SetField set the crontab field at index i

func (CrontabLine) Sort

func (cl CrontabLine) Sort()

Sort the crontab sub-elements chronologically

func (CrontabLine) String

func (cl CrontabLine) String() string

func (CrontabLine) Validate

func (cl CrontabLine) Validate() error

Validate return an error if the crontab line is invalid

type DayUnit

type DayUnit struct{}

DayUnit units in days

func (DayUnit) Add

func (DayUnit) Add(t time.Time, n int) time.Time

func (DayUnit) Less

func (DayUnit) Less(u Unit) bool

func (DayUnit) String

func (DayUnit) String() string

func (DayUnit) Trunc

func (DayUnit) Trunc(t time.Time) time.Time

type ErrorBadIndex

type ErrorBadIndex struct {
	FieldName string
	Value     int
}

func (*ErrorBadIndex) Error

func (i *ErrorBadIndex) Error() string

type ErrorBadName

type ErrorBadName struct {
	FieldName string
	Value     string
}

func (*ErrorBadName) Error

func (i *ErrorBadName) Error() string

type ErrorParse

type ErrorParse struct {
	Index int
	State State
}

func (*ErrorParse) Error

func (q *ErrorParse) Error() string

type FieldConfig

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

FieldConfig models the forms of time component ranges

func (FieldConfig) Ceil

func (configField FieldConfig) Ceil(tabField CrontabField, t time.Time) (time.Time, bool)

Ceil performs a ceiling function for a calendar unit within the constraints of the crontab

type HourUnit

type HourUnit struct{}

HourUnit units in hours

func (HourUnit) Add

func (HourUnit) Add(t time.Time, n int) time.Time

func (HourUnit) Less

func (x HourUnit) Less(u Unit) bool

func (HourUnit) String

func (HourUnit) String() string

func (HourUnit) Trunc

func (HourUnit) Trunc(t time.Time) time.Time

type MinuteUnit

type MinuteUnit struct{}

MinuteUnit units in minutes

func (MinuteUnit) Add

func (MinuteUnit) Add(t time.Time, n int) time.Time

func (MinuteUnit) Less

func (MinuteUnit) Less(u Unit) bool

func (MinuteUnit) String

func (MinuteUnit) String() string

func (MinuteUnit) Trunc

func (MinuteUnit) Trunc(t time.Time) time.Time

type MonthUnit

type MonthUnit struct{}

MonthUnit units in months

func (MonthUnit) Add

func (MonthUnit) Add(t time.Time, n int) time.Time

func (MonthUnit) Less

func (MonthUnit) Less(u Unit) bool

func (MonthUnit) String

func (MonthUnit) String() string

func (MonthUnit) Trunc

func (MonthUnit) Trunc(t time.Time) time.Time

type SecondUnit

type SecondUnit struct{}

SecondUnit units in seconds

func (SecondUnit) Add

func (SecondUnit) Add(t time.Time, n int) time.Time

func (SecondUnit) Less

func (SecondUnit) Less(u Unit) bool

func (SecondUnit) String

func (SecondUnit) String() string

func (SecondUnit) Trunc

func (SecondUnit) Trunc(t time.Time) time.Time

type State

type State int

type Unit

type Unit interface {
	// Less return true if this Unit is a finer grain than the supplied Unit, x
	Less(x Unit) bool
	// String return a simple name for the unit.
	String() string
	// Add returns time, t, with n units added
	Add(t time.Time, n int) time.Time
	// Trunc returns a time with all the lower components zeroed.
	Trunc(t time.Time) time.Time
}

Unit units of time

type WeekOfMonth

type WeekOfMonth struct{}

WeekOfMonth units in week in month ordinal

Example

crontab event at second saturday of every month

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/aalpar/cronfab"
)

func main() {
	markers, err := cronfab.SecondContabConfig.ParseCronTab("1 1 1 * 2 * sat")
	if err != nil {
		fmt.Printf("err: %v\n", err)
	}
	fmt.Printf("%v\n", markers)

	t1 := time.Now()
	// run for 4 intervals
	for i := 0; i < 4; i++ {
		t1, err = cronfab.SecondContabConfig.Next(markers, t1)
		if err != nil {
			fmt.Printf("err: %v\n", err)
			return
		}
		fmt.Fprintf(os.Stderr, "time: %v\n", t1)
	}

}
Output:

1-1/1 1-1/1 1-1/1 1-31/1 2-2/1 1-12/1 6-6/1

func (WeekOfMonth) Add

func (WeekOfMonth) Add(t time.Time, n int) time.Time

func (WeekOfMonth) Less

func (WeekOfMonth) Less(u Unit) bool

func (WeekOfMonth) String

func (WeekOfMonth) String() string

func (WeekOfMonth) Trunc

func (WeekOfMonth) Trunc(t time.Time) time.Time

type YearUnit

type YearUnit struct{}

YearUnit units in years

func (YearUnit) Add

func (YearUnit) Add(t time.Time, n int) time.Time

func (YearUnit) Less

func (YearUnit) Less(u Unit) bool

func (YearUnit) String

func (YearUnit) String() string

func (YearUnit) Trunc

func (YearUnit) Trunc(t time.Time) time.Time

Jump to

Keyboard shortcuts

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