package cronimport ()// Cron keeps track of any number of entries, invoking the associated func as// specified by the schedule. It may be started, stopped, and the entries may// be inspected while running.typeCronstruct { entries []*Entry chain Chain stop chanstruct{} add chan *Entry remove chanEntryID snapshot chanchan []Entry running bool logger Logger runningMu sync.Mutex location *time.Location parser ScheduleParser nextID EntryID jobWaiter sync.WaitGroup}// ScheduleParser is an interface for schedule spec parsers that return a ScheduletypeScheduleParserinterface {Parse(spec string) (Schedule, error)}// Job is an interface for submitted cron jobs.typeJobinterface {Run()}// Schedule describes a job's duty cycle.typeScheduleinterface {// Next returns 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}// EntryID identifies an entry within a Cron instancetypeEntryIDint// Entry consists of a schedule and the func to execute on that schedule.typeEntrystruct {// ID is the cron-assigned ID of this entry, which may be used to look up a // snapshot or remove it. ID EntryID// Schedule on which this job should be run. Schedule Schedule// Next time the job will run, or the zero time if Cron has not been // started or this entry's schedule is unsatisfiable Next time.Time// Prev is the last time this job was run, or the zero time if never. Prev time.Time// WrappedJob is the thing to run when the Schedule is activated. WrappedJob Job// Job is the thing that was submitted to cron. // It is kept around so that user code that needs to get at the job later, // e.g. via Entries() can do so. Job Job}// Valid returns true if this is not the zero entry.func ( Entry) () bool { return .ID != 0 }// byTime is a wrapper for sorting the entry array by time// (with zero time at the end).type byTime []*Entryfunc ( byTime) () int { returnlen() }func ( byTime) (, int) { [], [] = [], [] }func ( byTime) (, int) bool {// Two zero times should return false. // Otherwise, zero is "greater" than any other time. // (To sort it at the end of the list.)if [].Next.IsZero() {returnfalse }if [].Next.IsZero() {returntrue }return [].Next.Before([].Next)}// New returns a new Cron job runner, modified by the given options.//// Available Settings//// Time Zone// Description: The time zone in which schedules are interpreted// Default: time.Local//// Parser// Description: Parser converts cron spec strings into cron.Schedules.// Default: Accepts this spec: https://en.wikipedia.org/wiki/Cron//// Chain// Description: Wrap submitted jobs to customize behavior.// Default: A chain that recovers panics and logs them to stderr.//// See "cron.With*" to modify the default behavior.func ( ...Option) *Cron { := &Cron{entries: nil,chain: NewChain(),add: make(chan *Entry),stop: make(chanstruct{}),snapshot: make(chanchan []Entry),remove: make(chanEntryID),running: false,runningMu: sync.Mutex{},logger: DefaultLogger,location: time.Local,parser: standardParser, }for , := range { () }return}// FuncJob is a wrapper that turns a func() into a cron.JobtypeFuncJobfunc()func ( FuncJob) () { () }// AddFunc adds a func to the Cron to be run on the given schedule.// The spec is parsed using the time zone of this Cron instance as the default.// An opaque ID is returned that can be used to later remove it.func ( *Cron) ( string, func()) (EntryID, error) {return .AddJob(, FuncJob())}// AddJob adds a Job to the Cron to be run on the given schedule.// The spec is parsed using the time zone of this Cron instance as the default.// An opaque ID is returned that can be used to later remove it.func ( *Cron) ( string, Job) (EntryID, error) { , := .parser.Parse()if != nil {return0, }return .Schedule(, ), nil}// Schedule adds a Job to the Cron to be run on the given schedule.// The job is wrapped with the configured Chain.func ( *Cron) ( Schedule, Job) EntryID { .runningMu.Lock()defer .runningMu.Unlock() .nextID++ := &Entry{ID: .nextID,Schedule: ,WrappedJob: .chain.Then(),Job: , }if !.running { .entries = append(.entries, ) } else { .add <- }return .ID}// Entries returns a snapshot of the cron entries.func ( *Cron) () []Entry { .runningMu.Lock()defer .runningMu.Unlock()if .running { := make(chan []Entry, 1) .snapshot <- return <- }return .entrySnapshot()}// Location gets the time zone locationfunc ( *Cron) () *time.Location {return .location}// Entry returns a snapshot of the given entry, or nil if it couldn't be found.func ( *Cron) ( EntryID) Entry {for , := range .Entries() {if == .ID {return } }returnEntry{}}// Remove an entry from being run in the future.func ( *Cron) ( EntryID) { .runningMu.Lock()defer .runningMu.Unlock()if .running { .remove <- } else { .removeEntry() }}// Start the cron scheduler in its own goroutine, or no-op if already started.func ( *Cron) () { .runningMu.Lock()defer .runningMu.Unlock()if .running {return } .running = truego .run()}// Run the cron scheduler, or no-op if already running.func ( *Cron) () { .runningMu.Lock()if .running { .runningMu.Unlock()return } .running = true .runningMu.Unlock() .run()}// run the scheduler.. this is private just due to the need to synchronize// access to the 'running' state variable.func ( *Cron) () { .logger.Info("start")// Figure out the next activation times for each entry. := .now()for , := range .entries { .Next = .Schedule.Next() .logger.Info("schedule", "now", , "entry", .ID, "next", .Next) }for {// Determine the next entry to run.sort.Sort(byTime(.entries))var *time.Timeriflen(.entries) == 0 || .entries[0].Next.IsZero() {// If there are no entries yet, just sleep - it still handles new entries // and stop requests. = time.NewTimer(100000 * time.Hour) } else { = time.NewTimer(.entries[0].Next.Sub()) }for {select {case = <-.C: = .In(.location) .logger.Info("wake", "now", )// Run every entry whose next time was less than nowfor , := range .entries {if .Next.After() || .Next.IsZero() {break } .startJob(.WrappedJob) .Prev = .Next .Next = .Schedule.Next() .logger.Info("run", "now", , "entry", .ID, "next", .Next) }case := <-.add: .Stop() = .now() .Next = .Schedule.Next() .entries = append(.entries, ) .logger.Info("added", "now", , "entry", .ID, "next", .Next)case := <-.snapshot: <- .entrySnapshot()continuecase<-.stop: .Stop() .logger.Info("stop")returncase := <-.remove: .Stop() = .now() .removeEntry() .logger.Info("removed", "entry", ) }break } }}// startJob runs the given job in a new goroutine.func ( *Cron) ( Job) { .jobWaiter.Add(1)gofunc() {defer .jobWaiter.Done() .Run() }()}// now returns current time in c locationfunc ( *Cron) () time.Time {returntime.Now().In(.location)}// Stop stops the cron scheduler if it is running; otherwise it does nothing.// A context is returned so the caller can wait for running jobs to complete.func ( *Cron) () context.Context { .runningMu.Lock()defer .runningMu.Unlock()if .running { .stop <- struct{}{} .running = false } , := context.WithCancel(context.Background())gofunc() { .jobWaiter.Wait() () }()return}// entrySnapshot returns a copy of the current cron entry list.func ( *Cron) () []Entry {var = make([]Entry, len(.entries))for , := range .entries { [] = * }return}func ( *Cron) ( EntryID) {var []*Entryfor , := range .entries {if .ID != { = append(, ) } } .entries = }
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.