crontab

package module
v0.0.0-...-93e68a5 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2020 License: MIT Imports: 8 Imported by: 0

README

Crontab and Schedule

This is an enhancement of the very useful crontab package from mileusna.

  • It provides a uniform and very flexible processing for execution stats from different scheduled jobs via a common/shared/global channel.
  • It checks the jobs to run (each minute, i.e. the most granular time frame according to the crontab rules) at the beginning of the minute (0 seconds, 000 milliseconds).
  • It gives a higher level definition of schedule via the Schedule interface, compared to the low level crontab logic regarding jobs scheduling.

Go/Golang package for Crontab tickers

This package provides crontab tickers to golang apps, supporting crontab-like syntax like * * * * * or */2 * * * * etc.

Installation

go get github.com/tappoz/crontab

Example

package main

import (
    "fmt"
    "log"

    "github.com/tappoz/crontab"
)

func main() {

    ctab := crontab.New() // create cron table

    // AddJob and test the errors
    err := ctab.AddJob("0 12 1 * *", myFunc) // on 1st day of month
    if err != nil {
        log.Println(err)
        return
    }    

    // MustAddJob is like AddJob but panics on wrong syntax or problems with func/args
    // This aproach is similar to regexp.Compile and regexp.MustCompile from go's standard library,  used for easier initialization on startup
    ctab.MustAddJob("* * * * *", myFunc) // every minute
    ctab.MustAddJob("0 12 * * *", myFunc3) // noon lauch

    // fn with args
    ctab.MustAddJob("0 0 * * 1,2", myFunc2, "Monday and Tuesday midnight", 123)
    ctab.MustAddJob("*/5 * * * *", myFunc2, "every five min", 0)

    // all your other app code as usual, or put sleep timer for demo
    // time.Sleep(10 * time.Minute)
}

func myFunc() {
    fmt.Println("Helo, world")
}

func myFunc3() {
    fmt.Println("Noon!")
}

func myFunc2(s string, n int) {
    fmt.Println("We have params here, string", s, "and number", n)
}

Crontab syntax

If you are not faimiliar with crontab syntax you might be better off with other packages for scheduling tasks. But if you are familiar with Linux and crontab, this package might be right for you.

Here are the few quick references about crontab simple but powerful syntax.

*     *     *     *     *        

^     ^     ^     ^     ^
|     |     |     |     |
|     |     |     |     +----- day of week (0-6) (Sunday=0)
|     |     |     +------- month (1-12)
|     |     +--------- day of month (1-31)
|     +----------- hour (0-23)
+------------- min (0-59)
Examples
  • * * * * * run on every minuta
  • 10 * * * * run at 0:10, 1:10 etc
  • 10 15 * * * run at 15:10 every day
  • * * 1 * * run on every minute on 1st day of month
  • 0 0 1 1 * Happy new year schedule
  • 0 0 * * 1 Run at midnight on every Monday
Lists
  • * 10,15,19 * * * run at 10:00, 15:00 and 19:00
  • 1-15 * * * * run at 1, 2, 3...15 minute of each hour
  • 0 0-5,10 * * * run on every hour from 0-5 and in 10 oclock
Steps
  • */2 * * * * run every two minutes
  • 10 */3 * * * run every 3 hours on 10th min
  • 0 12 */2 * * run at noon on every two days
  • 1-59/2 * * * run every two minutes, but on odd minutes

Notice

There is no way to reschedule or to remove single job from crontab during runtime with crontab package. (Re)create new instance of crontab or use crontab.Clear() function and then add jobs again to reschedule during runtime.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BlockingStatsConsumer

func BlockingStatsConsumer(ctab *Crontab, statsConsumerFunc StstsConsumerFunc)

BlockingStatsConsumer is a unified way of consuming stats

func ScheduleAll

func ScheduleAll(ctab *Crontab, schedules ...Schedule) error

ScheduleAll is a static function invoking all the schedules implementing the interface. These schedule functions are invoked against the crontab instance

Types

type Crontab

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

Crontab struct representing cron table

func New

func New(disableSleepToBeginningOfMinute ...bool) *Crontab

New initializes and returns new cron table. By default it waits until the beginning of the next minute (00 seconds, 000 milliseconds) before initializing the ticker to disable this then pass a boolean flag as input parameter

func (*Crontab) AddJob

func (c *Crontab) AddJob(schedule string, fn interface{}, args ...interface{}) error

AddJob to cron table

Returns error if:

* Cron syntax can't be parsed or out of bounds

* fn is not function

* Provided args don't match the number and/or the type of fn args

func (*Crontab) Clear

func (c *Crontab) Clear()

Clear all jobs from cron table

func (*Crontab) MustAddJob

func (c *Crontab) MustAddJob(schedule string, fn interface{}, args ...interface{})

MustAddJob is like AddJob but panics if there is an problem with job

It simplifies initialization, since we usually add jobs at the beggining so you won't have to check for errors (it will panic when program starts). It is a similar aproach as go's std lib package `regexp` and `regexp.Compile()` `regexp.MustCompile()` MustAddJob will panic if:

* Cron syntax can't be parsed or out of bounds

* fn is not function

* Provided args don't match the number and/or the type of fn args

func (*Crontab) RunAll

func (c *Crontab) RunAll()

RunAll jobs in cron table, shcheduled or not

func (*Crontab) Shutdown

func (c *Crontab) Shutdown()

Shutdown the cron table schedule

Once stopped, it can't be restarted. This function is pre-shuttdown helper for your app, there is no Start/Stop functionallity with crontab package.

func (*Crontab) StatsChan

func (c *Crontab) StatsChan() chan ExecStats

StatsChan returns the channel to consume execution statistics

type ExecStats

type ExecStats struct {
	JobType string
	Stats   StatsData
}

ExecStats struct representing a standardized wrapper for execution statistics. If a job is to be considered of multiple steps - each of them could partially fail, then: * When some of these steps are in error, then the flag `StatsMessage()` should be true. * When all the steps are in error, then the flag `TotalError()` should be true.

Both flags should help whatever is supposed to parse an arbitrary structure representing the Job by implementing the `StatsData` interface and made of both execution stats and error.

type InvokeFunc

type InvokeFunc func(statsChan chan ExecStats)

InvokeFunc represent the function containing the logic to schedule as a job. It is handy because it allows to submit stats about the job execution in a unified way via the channel as definded in the `crontab` interface.

type Schedule

type Schedule interface {
	CrontabSyntax() string
	Invoke()
	Description() string
}

Schedule represents a Job to be executed from a high-level point of view i.e is a unified interface that can be treated in a standard way by other parts, but allows to inject any kind of custom logic via the constructor `NewSchedule` which expect just a function of type `InvokeFunc` that could be provided containing any logic.

func NewSchedule

func NewSchedule(crontabSyntax string, description string, invokeFunction InvokeFunc, statsChan chan ExecStats) Schedule

NewSchedule creates a new Schedule object containing common configuration parameters like the crontab syntax (e.g. `* * * * *`), a description for the schedule, the Invoke Func containing the job implementation and a global channel for stats shared between all the jobs.

type StatsData

type StatsData interface {
	// JSONString is a general purpose function to provide an aggregated view/message for the stats.
	// It is intended as a valid JSON string representation of the stats.
	JSONString() string
	// ErrorMessage is a function to focus only on the errors that might have been recorded in the `StatsData`.
	// This should be useful in combination with `ExecuteStats.Stats.SomePartialErrors()` and `ExecuteStats.Stats.TotalError`
	// when dealing with complex schedules made of steps and half-done work due to partial success of some of these steps.
	ErrorMessage() string
	// StatsMessage is a function intended for the scenario where a message with the
	// aggregated stats is needed, but no JSON string is required, just a message in Natural Language
	// injected with the aggregated stats from `StatsData` (whatever structure it might have).
	StatsMessage() string

	// SomePartialErrors should tell if there are some (partial) errors (any) in the execution
	// e.g. some half-done work where some steps are successful and other steps are not successful.
	// This depends on the structure of the Go `struct` the developer writes to implement
	// the interface `StatsData` for the specific job that is being executed.
	SomePartialErrors() bool
	// TotalError should tell if the whole execution is to be considered in error
	// e.g. when there is a complete failure of the job.
	TotalError() bool
}

StatsData is an interface representing a custom execution statistics for an arbitrary job/schedule. It provides some general purpose functions to inspects an arbitrary statistics about a job execution.

type StstsConsumerFunc

type StstsConsumerFunc func(stats ExecStats)

StstsConsumerFunc provides a unified way of consuming execution stats from various independent schedules.

Jump to

Keyboard shortcuts

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