crontab

package
v1.0.17 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: BSD-2-Clause Imports: 8 Imported by: 0

README

cronlib

Cronlib is easy golang crontab library, support parse crontab and schedule cron jobs.

cron_parser.go import https://github.com/robfig/cron/blob/master/parser.go, thank @robfig

Feature

  • thread safe
  • add try catch mode
  • dynamic modify job cron
  • dynamic add job
  • stop service job
  • add Wait method for waiting all job exit
  • async & sync mode

Usage

see more example

quick run
package main

import (
	"log"

	"github.com/rfyiamcool/cronlib"
)

var (
	cron = cronlib.New()
)

func main() {
	handleClean()
	go start()

	// cron already start, dynamic add job
	handleBackup()

	select {}
}

func start() {
	cron.Start()
	cron.Wait()
}

func handleClean() {
	job, err := cronlib.NewJobModel(
		"*/5 * * * * *",
		func() {
			pstdout("do clean gc action")
		},
	)
	if err != nil {
		panic(err.Error())
	}

	err = cron.Register("clean", job)
	if err != nil {
		panic(err.Error())
	}
}

func handleBackup() {
	job, err := cronlib.NewJobModel(
		"*/5 * * * * *",
		func() {
			pstdout("do backup action")
		},
	)
	if err != nil {
		panic(err.Error())
	}

	err = cron.DynamicRegister("backup", job)
	if err != nil {
		panic(err.Error())
	}
}

func pstdout(srv string) {
	log.Println(srv)
}
set job attr

open async mode and try catch mode

func run() error {
	cron := cronlib.New()

	// set async mode
	job, err = cronlib.NewJobModel(
		"0 * * * * *",
		func(),
		cronlib.AsyncMode(),
		cronlib.TryCatchMode(),
	)

	...
}

other method

func run() error {
	cron := cronlib.New()

	// set async mode
	job, err = cronlib.NewJobModel(
		"0 * * * * *",
		func(),
	)

	...

	job.SetTryCatch(cronlib.OnMode)
	job.SetAsyncMode(cronlib.OnMode)

	...
}

stop job
cron := cronlib.New()
...
cron.StopService(srvName)
update job
spec := "*/3 * * * * *"
srv := "risk.scan.total.5s.to.3s"

job, _ := cronlib.NewJobModel(
	spec,
	func() {
		stdout(srv, spec)
	},
)

err := cron.UpdateJobModel(srv, job)
...

Example

package main

// test for crontab spec

import (
	"log"
	"time"

	"github.com/rfyiamcool/cronlib"
)

func main() {
	cron := cronlib.New()

	specList := map[string]string{
		"risk.scan.total.1s":       "*/1 * * * * *",
		"risk.scan.total.2s":       "*/2 * * * * *",
		"risk.scan.total.3s":       "*/3 * * * * *",
		"risk.scan.total.4s":       "*/4 * * * * *",
		"risk.scan.total.5s.to.3s": "*/5 * * * * *",
	}

	for srv, spec := range specList {
		tspec := spec // copy
		ssrv := srv   // copy
		job, err := cronlib.NewJobModel(
			spec,
			func() {
				stdout(ssrv, tspec)
			},
		)
		if err != nil {
			panic(err.Error())
		}

		err = cron.Register(srv, job)
		if err != nil {
			panic(err.Error())
		}
	}

	// update test
	time.AfterFunc(10*time.Second, func() {
		spec := "*/3 * * * * *"
		srv := "risk.scan.total.5s.to.3s"
		log.Println("reset 5s to 3s", srv)
		job, _ := cronlib.NewJobModel(
			spec,
			func() {
				stdout(srv, spec)
			},
		)
		cron.UpdateJobModel(srv, job)
		log.Println("reset finish", srv)

	})

	// kill test
	time.AfterFunc(3*time.Second, func() {

		srv := "risk.scan.total.1s"
		log.Println("stoping", srv)
		cron.StopService(srv)
		log.Println("stop finish", srv)

	})

	time.AfterFunc(11*time.Second, func() {

		srvPrefix := "risk"
		log.Println("stoping srv prefix", srvPrefix)
		cron.StopServicePrefix(srvPrefix)

	})

	cron.Start()
	cron.Wait()
}

func stdout(srv, spec string) {
	log.Println(srv, spec)
}

Time Format Usage:

cronlib has second field, cronlibs contains six fields, first field is second than linux crontab

every 2 seconds

*/2 * * * * *

every hour on the half hour

0 30 * * * *

detail field desc


Field name   | Mandatory? | Allowed values  | Allowed special characters
----------   | ---------- | --------------  | --------------------------
Seconds      | Yes        | 0-59            | * / , -
Minutes      | Yes        | 0-59            | * / , -
Hours        | Yes        | 0-23            | * / , -
Day of month | Yes        | 1-31            | * / , - ?
Month        | Yes        | 1-12 or JAN-DEC | * / , -
Day of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?

cron parse doc: https://github.com/robfig/cron

Documentation

Index

Constants

View Source
const (
	OnMode  = true
	OffMode = false
)

Variables

View Source
var (
	ErrNotFoundJob     = errors.New("not found job")
	ErrAlreadyRegister = errors.New("the job already in pool")
	ErrJobDOFuncNil    = errors.New("callback func is nil")
	ErrCronSpecInvalid = errors.New("crontab spec is invalid")
)

Functions

func SetLogger added in v1.0.17

func SetLogger(logger loggerType)

func SetPanicCaller added in v1.0.17

func SetPanicCaller(p panicType)

Types

type ConstantDelaySchedule added in v1.0.17

type ConstantDelaySchedule struct {
	Delay time.Duration
}

ConstantDelaySchedule represents a simple recurring duty cycle, e.g. "Every 5 minutes". It does not support jobs more frequent than once a second.

func Every added in v1.0.17

func Every(duration time.Duration) ConstantDelaySchedule

Every returns a crontab Schedule that activates once every duration. Delays of less than a second are not supported (will round up to 1 second). Any fields less than a Second are truncated.

func (ConstantDelaySchedule) Next added in v1.0.17

func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time

Next returns the next time this should be run. This rounds so that the next activation time will be on the second.

type CronSchduler added in v1.0.17

type CronSchduler struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

CronSchduler

func New

func New() *CronSchduler

New - create CronSchduler

func (*CronSchduler) DynamicRegister added in v1.0.17

func (c *CronSchduler) DynamicRegister(srv string, model *JobModel) error

DynamicRegister - after cronlib already run, dynamic add a job, the job autostart by cronlib.

func (*CronSchduler) GetServiceCron added in v1.0.17

func (c *CronSchduler) GetServiceCron(srv string) (*JobModel, error)

func (*CronSchduler) Register added in v1.0.17

func (c *CronSchduler) Register(srv string, model *JobModel) error

Register - only register srv's job model, don't start auto.

func (*CronSchduler) Start added in v1.0.17

func (c *CronSchduler) Start()

func (*CronSchduler) Stop added in v1.0.17

func (c *CronSchduler) Stop()

Stop - stop all cron job

func (*CronSchduler) StopService added in v1.0.17

func (c *CronSchduler) StopService(srv string)

StopService - stop job by serviceName

func (*CronSchduler) StopServicePrefix added in v1.0.17

func (c *CronSchduler) StopServicePrefix(regex string)

StopServicePrefix - stop job by srv regex prefix. if regex = "risk.scan", stop risk.scan.total, risk.scan.user at the same time

func (*CronSchduler) UnRegister added in v1.0.17

func (c *CronSchduler) UnRegister(srv string) error

UnRegister - stop and delete srv

func (*CronSchduler) UpdateJobModel added in v1.0.17

func (c *CronSchduler) UpdateJobModel(srv string, model *JobModel) error

UpdateJobModel - stop old job, update srv's job model

func (*CronSchduler) Wait added in v1.0.17

func (c *CronSchduler) Wait()

Wait - if all jobs is exited, return.

func (*CronSchduler) WaitStop added in v1.0.17

func (c *CronSchduler) WaitStop()

WaitStop - when stop cronlib controller, return.

type JobModel added in v1.0.17

type JobModel struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewJobModel added in v1.0.17

func NewJobModel(spec string, f func(), options ...JobOption) (*JobModel, error)

NewJobModel - defualt block sync callfunc

func (*JobModel) SetAsyncMode added in v1.0.17

func (j *JobModel) SetAsyncMode(b bool)

func (*JobModel) SetTryCatch added in v1.0.17

func (j *JobModel) SetTryCatch(b bool)

type JobOption added in v1.0.17

type JobOption func(*JobModel) error

func AsyncMode added in v1.0.17

func AsyncMode() JobOption

func TryCatchMode added in v1.0.17

func TryCatchMode() JobOption

type ParseOption added in v1.0.17

type ParseOption int

Configuration options for creating a parser. Most options specify which fields should be included, while others enable features. If a field is not included the parser will assume a default value. These options do not change the order fields are parse in.

const (
	Second      ParseOption = 1 << iota // Seconds field, default 0
	Minute                              // Minutes field, default 0
	Hour                                // Hours field, default 0
	Dom                                 // Day of month field, default *
	Month                               // Month field, default *
	Dow                                 // Day of week field, default *
	DowOptional                         // Optional day of week field, default *
	Descriptor                          // Allow descriptors such as @monthly, @weekly, etc.
)

type Parser added in v1.0.17

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

A custom Parser that can be configured.

func NewParser added in v1.0.17

func NewParser(options ParseOption) Parser

Creates a custom Parser with custom options.

// Standard parser without descriptors
specParser := NewParser(Minute | Hour | Dom | Month | Dow)
sched, err := specParser.Parse("0 0 15 */3 *")

// Same as above, just excludes time fields
subsParser := NewParser(Dom | Month | Dow)
sched, err := specParser.Parse("15 */3 *")

// Same as above, just makes Dow optional
subsParser := NewParser(Dom | Month | DowOptional)
sched, err := specParser.Parse("15 */3")

func (Parser) Parse added in v1.0.17

func (p Parser) Parse(spec string) (TimeRunner, error)

Parse returns a new crontab schedule representing the given spec. It returns a descriptive error if the spec is not valid. It accepts crontab specs and features configured by NewParser.

type SpecSchedule added in v1.0.17

type SpecSchedule struct {
	Second, Minute, Hour, Dom, Month, Dow uint64
}

SpecSchedule specifies a duty cycle (to the second granularity), based on a traditional crontab specification. It is computed initially and stored as bit sets.

func (*SpecSchedule) Next added in v1.0.17

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

Next returns the next time this schedule is activated, greater than the given time. If no time can be found to satisfy the schedule, return the zero time.

type TimeRunner added in v1.0.17

type TimeRunner interface {
	// Return the next activation time, later than the given time.
	// Next is invoked initially, and then each time the job is run.
	Next(time.Time) time.Time
}

The Schedule describes a job's duty cycle.

func Parse added in v1.0.17

func Parse(spec string) (TimeRunner, error)

Parse returns a new crontab schedule representing the given spec. It returns a descriptive error if the spec is not valid.

It accepts

  • Full crontab specs, e.g. "* * * * * ?"
  • Descriptors, e.g. "@midnight", "@every 1h30m"

func ParseStandard added in v1.0.17

func ParseStandard(standardSpec string) (TimeRunner, error)

ParseStandard returns a new crontab schedule representing the given standardSpec (https://en.wikipedia.org/wiki/Cron). It differs from Parse requiring to always pass 5 entries representing: minute, hour, day of month, month and day of week, in that order. It returns a descriptive error if the spec is not valid.

It accepts

  • Standard crontab specs, e.g. "* * * * ?"
  • Descriptors, e.g. "@midnight", "@every 1h30m"

Jump to

Keyboard shortcuts

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