[
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.exe\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: go\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (C) 2012 Rob Figueiredo\nAll Rights Reserved.\n\nMIT LICENSE\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "[![GoDoc](http://godoc.org/github.com/robfig/cron?status.png)](http://godoc.org/github.com/robfig/cron)\n[![Build Status](https://travis-ci.org/robfig/cron.svg?branch=master)](https://travis-ci.org/robfig/cron)\n\n# cron\n\nCron V3 has been released!\n\nTo download the specific tagged release, run:\n```bash\ngo get github.com/robfig/cron/v3@v3.0.0\n```\nImport it in your program as:\n```go\nimport \"github.com/robfig/cron/v3\"\n```\nIt requires Go 1.11 or later due to usage of Go Modules.\n\nRefer to the documentation here:\nhttp://godoc.org/github.com/robfig/cron\n\nThe rest of this document describes the the advances in v3 and a list of\nbreaking changes for users that wish to upgrade from an earlier version.\n\n## Upgrading to v3 (June 2019)\n\ncron v3 is a major upgrade to the library that addresses all outstanding bugs,\nfeature requests, and rough edges. It is based on a merge of master which\ncontains various fixes to issues found over the years and the v2 branch which\ncontains some backwards-incompatible features like the ability to remove cron\njobs. In addition, v3 adds support for Go Modules, cleans up rough edges like\nthe timezone support, and fixes a number of bugs.\n\nNew features:\n\n- Support for Go modules. Callers must now import this library as\n  `github.com/robfig/cron/v3`, instead of `gopkg.in/...`\n\n- Fixed bugs:\n  - 0f01e6b parser: fix combining of Dow and Dom (#70)\n  - dbf3220 adjust times when rolling the clock forward to handle non-existent midnight (#157)\n  - eeecf15 spec_test.go: ensure an error is returned on 0 increment (#144)\n  - 70971dc cron.Entries(): update request for snapshot to include a reply channel (#97)\n  - 1cba5e6 cron: fix: removing a job causes the next scheduled job to run too late (#206)\n\n- Standard cron spec parsing by default (first field is \"minute\"), with an easy\n  way to opt into the seconds field (quartz-compatible). Although, note that the\n  year field (optional in Quartz) is not supported.\n\n- Extensible, key/value logging via an interface that complies with\n  the https://github.com/go-logr/logr project.\n\n- The new Chain & JobWrapper types allow you to install \"interceptors\" to add\n  cross-cutting behavior like the following:\n  - Recover any panics from jobs\n  - Delay a job's execution if the previous run hasn't completed yet\n  - Skip a job's execution if the previous run hasn't completed yet\n  - Log each job's invocations\n  - Notification when jobs are completed\n\nIt is backwards incompatible with both v1 and v2. These updates are required:\n\n- The v1 branch accepted an optional seconds field at the beginning of the cron\n  spec. This is non-standard and has led to a lot of confusion. The new default\n  parser conforms to the standard as described by [the Cron wikipedia page].\n\n  UPDATING: To retain the old behavior, construct your Cron with a custom\n  parser:\n```go\n// Seconds field, required\ncron.New(cron.WithSeconds())\n\n// Seconds field, optional\ncron.New(cron.WithParser(cron.NewParser(\n\tcron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,\n)))\n```\n- The Cron type now accepts functional options on construction rather than the\n  previous ad-hoc behavior modification mechanisms (setting a field, calling a setter).\n\n  UPDATING: Code that sets Cron.ErrorLogger or calls Cron.SetLocation must be\n  updated to provide those values on construction.\n\n- CRON_TZ is now the recommended way to specify the timezone of a single\n  schedule, which is sanctioned by the specification. The legacy \"TZ=\" prefix\n  will continue to be supported since it is unambiguous and easy to do so.\n\n  UPDATING: No update is required.\n\n- By default, cron will no longer recover panics in jobs that it runs.\n  Recovering can be surprising (see issue #192) and seems to be at odds with\n  typical behavior of libraries. Relatedly, the `cron.WithPanicLogger` option\n  has been removed to accommodate the more general JobWrapper type.\n\n  UPDATING: To opt into panic recovery and configure the panic logger:\n```go\ncron.New(cron.WithChain(\n  cron.Recover(logger),  // or use cron.DefaultLogger\n))\n```\n- In adding support for https://github.com/go-logr/logr, `cron.WithVerboseLogger` was\n  removed, since it is duplicative with the leveled logging.\n\n  UPDATING: Callers should use `WithLogger` and specify a logger that does not\n  discard `Info` logs. For convenience, one is provided that wraps `*log.Logger`:\n```go\ncron.New(\n  cron.WithLogger(cron.VerbosePrintfLogger(logger)))\n```\n\n### Background - Cron spec format\n\nThere are two cron spec formats in common usage:\n\n- The \"standard\" cron format, described on [the Cron wikipedia page] and used by\n  the cron Linux system utility.\n\n- The cron format used by [the Quartz Scheduler], commonly used for scheduled\n  jobs in Java software\n\n[the Cron wikipedia page]: https://en.wikipedia.org/wiki/Cron\n[the Quartz Scheduler]: http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/tutorial-lesson-06.html\n\nThe original version of this package included an optional \"seconds\" field, which\nmade it incompatible with both of these formats. Now, the \"standard\" format is\nthe default format accepted, and the Quartz format is opt-in.\n"
  },
  {
    "path": "chain.go",
    "content": "package cron\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\n// JobWrapper decorates the given Job with some behavior.\ntype JobWrapper func(Job) Job\n\n// Chain is a sequence of JobWrappers that decorates submitted jobs with\n// cross-cutting behaviors like logging or synchronization.\ntype Chain struct {\n\twrappers []JobWrapper\n}\n\n// NewChain returns a Chain consisting of the given JobWrappers.\nfunc NewChain(c ...JobWrapper) Chain {\n\treturn Chain{c}\n}\n\n// Then decorates the given job with all JobWrappers in the chain.\n//\n// This:\n//     NewChain(m1, m2, m3).Then(job)\n// is equivalent to:\n//     m1(m2(m3(job)))\nfunc (c Chain) Then(j Job) Job {\n\tfor i := range c.wrappers {\n\t\tj = c.wrappers[len(c.wrappers)-i-1](j)\n\t}\n\treturn j\n}\n\n// Recover panics in wrapped jobs and log them with the provided logger.\nfunc Recover(logger Logger) JobWrapper {\n\treturn func(j Job) Job {\n\t\treturn FuncJob(func() {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tconst size = 64 << 10\n\t\t\t\t\tbuf := make([]byte, size)\n\t\t\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\t\t\t\terr, ok := r.(error)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\terr = fmt.Errorf(\"%v\", r)\n\t\t\t\t\t}\n\t\t\t\t\tlogger.Error(err, \"panic\", \"stack\", \"...\\n\"+string(buf))\n\t\t\t\t}\n\t\t\t}()\n\t\t\tj.Run()\n\t\t})\n\t}\n}\n\n// DelayIfStillRunning serializes jobs, delaying subsequent runs until the\n// previous one is complete. Jobs running after a delay of more than a minute\n// have the delay logged at Info.\nfunc DelayIfStillRunning(logger Logger) JobWrapper {\n\treturn func(j Job) Job {\n\t\tvar mu sync.Mutex\n\t\treturn FuncJob(func() {\n\t\t\tstart := time.Now()\n\t\t\tmu.Lock()\n\t\t\tdefer mu.Unlock()\n\t\t\tif dur := time.Since(start); dur > time.Minute {\n\t\t\t\tlogger.Info(\"delay\", \"duration\", dur)\n\t\t\t}\n\t\t\tj.Run()\n\t\t})\n\t}\n}\n\n// SkipIfStillRunning skips an invocation of the Job if a previous invocation is\n// still running. It logs skips to the given logger at Info level.\nfunc SkipIfStillRunning(logger Logger) JobWrapper {\n\treturn func(j Job) Job {\n\t\tvar ch = make(chan struct{}, 1)\n\t\tch <- struct{}{}\n\t\treturn FuncJob(func() {\n\t\t\tselect {\n\t\t\tcase v := <-ch:\n\t\t\t\tdefer func() { ch <- v }()\n\t\t\t\tj.Run()\n\t\t\tdefault:\n\t\t\t\tlogger.Info(\"skip\")\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "chain_test.go",
    "content": "package cron\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"reflect\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc appendingJob(slice *[]int, value int) Job {\n\tvar m sync.Mutex\n\treturn FuncJob(func() {\n\t\tm.Lock()\n\t\t*slice = append(*slice, value)\n\t\tm.Unlock()\n\t})\n}\n\nfunc appendingWrapper(slice *[]int, value int) JobWrapper {\n\treturn func(j Job) Job {\n\t\treturn FuncJob(func() {\n\t\t\tappendingJob(slice, value).Run()\n\t\t\tj.Run()\n\t\t})\n\t}\n}\n\nfunc TestChain(t *testing.T) {\n\tvar nums []int\n\tvar (\n\t\tappend1 = appendingWrapper(&nums, 1)\n\t\tappend2 = appendingWrapper(&nums, 2)\n\t\tappend3 = appendingWrapper(&nums, 3)\n\t\tappend4 = appendingJob(&nums, 4)\n\t)\n\tNewChain(append1, append2, append3).Then(append4).Run()\n\tif !reflect.DeepEqual(nums, []int{1, 2, 3, 4}) {\n\t\tt.Error(\"unexpected order of calls:\", nums)\n\t}\n}\n\nfunc TestChainRecover(t *testing.T) {\n\tpanickingJob := FuncJob(func() {\n\t\tpanic(\"panickingJob panics\")\n\t})\n\n\tt.Run(\"panic exits job by default\", func(t *testing.T) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err == nil {\n\t\t\t\tt.Errorf(\"panic expected, but none received\")\n\t\t\t}\n\t\t}()\n\t\tNewChain().Then(panickingJob).\n\t\t\tRun()\n\t})\n\n\tt.Run(\"Recovering JobWrapper recovers\", func(t *testing.T) {\n\t\tNewChain(Recover(PrintfLogger(log.New(ioutil.Discard, \"\", 0)))).\n\t\t\tThen(panickingJob).\n\t\t\tRun()\n\t})\n\n\tt.Run(\"composed with the *IfStillRunning wrappers\", func(t *testing.T) {\n\t\tNewChain(Recover(PrintfLogger(log.New(ioutil.Discard, \"\", 0)))).\n\t\t\tThen(panickingJob).\n\t\t\tRun()\n\t})\n}\n\ntype countJob struct {\n\tm       sync.Mutex\n\tstarted int\n\tdone    int\n\tdelay   time.Duration\n}\n\nfunc (j *countJob) Run() {\n\tj.m.Lock()\n\tj.started++\n\tj.m.Unlock()\n\ttime.Sleep(j.delay)\n\tj.m.Lock()\n\tj.done++\n\tj.m.Unlock()\n}\n\nfunc (j *countJob) Started() int {\n\tdefer j.m.Unlock()\n\tj.m.Lock()\n\treturn j.started\n}\n\nfunc (j *countJob) Done() int {\n\tdefer j.m.Unlock()\n\tj.m.Lock()\n\treturn j.done\n}\n\nfunc TestChainDelayIfStillRunning(t *testing.T) {\n\n\tt.Run(\"runs immediately\", func(t *testing.T) {\n\t\tvar j countJob\n\t\twrappedJob := NewChain(DelayIfStillRunning(DiscardLogger)).Then(&j)\n\t\tgo wrappedJob.Run()\n\t\ttime.Sleep(2 * time.Millisecond) // Give the job 2ms to complete.\n\t\tif c := j.Done(); c != 1 {\n\t\t\tt.Errorf(\"expected job run once, immediately, got %d\", c)\n\t\t}\n\t})\n\n\tt.Run(\"second run immediate if first done\", func(t *testing.T) {\n\t\tvar j countJob\n\t\twrappedJob := NewChain(DelayIfStillRunning(DiscardLogger)).Then(&j)\n\t\tgo func() {\n\t\t\tgo wrappedJob.Run()\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t\tgo wrappedJob.Run()\n\t\t}()\n\t\ttime.Sleep(3 * time.Millisecond) // Give both jobs 3ms to complete.\n\t\tif c := j.Done(); c != 2 {\n\t\t\tt.Errorf(\"expected job run twice, immediately, got %d\", c)\n\t\t}\n\t})\n\n\tt.Run(\"second run delayed if first not done\", func(t *testing.T) {\n\t\tvar j countJob\n\t\tj.delay = 10 * time.Millisecond\n\t\twrappedJob := NewChain(DelayIfStillRunning(DiscardLogger)).Then(&j)\n\t\tgo func() {\n\t\t\tgo wrappedJob.Run()\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t\tgo wrappedJob.Run()\n\t\t}()\n\n\t\t// After 5ms, the first job is still in progress, and the second job was\n\t\t// run but should be waiting for it to finish.\n\t\ttime.Sleep(5 * time.Millisecond)\n\t\tstarted, done := j.Started(), j.Done()\n\t\tif started != 1 || done != 0 {\n\t\t\tt.Error(\"expected first job started, but not finished, got\", started, done)\n\t\t}\n\n\t\t// Verify that the second job completes.\n\t\ttime.Sleep(25 * time.Millisecond)\n\t\tstarted, done = j.Started(), j.Done()\n\t\tif started != 2 || done != 2 {\n\t\t\tt.Error(\"expected both jobs done, got\", started, done)\n\t\t}\n\t})\n\n}\n\nfunc TestChainSkipIfStillRunning(t *testing.T) {\n\n\tt.Run(\"runs immediately\", func(t *testing.T) {\n\t\tvar j countJob\n\t\twrappedJob := NewChain(SkipIfStillRunning(DiscardLogger)).Then(&j)\n\t\tgo wrappedJob.Run()\n\t\ttime.Sleep(2 * time.Millisecond) // Give the job 2ms to complete.\n\t\tif c := j.Done(); c != 1 {\n\t\t\tt.Errorf(\"expected job run once, immediately, got %d\", c)\n\t\t}\n\t})\n\n\tt.Run(\"second run immediate if first done\", func(t *testing.T) {\n\t\tvar j countJob\n\t\twrappedJob := NewChain(SkipIfStillRunning(DiscardLogger)).Then(&j)\n\t\tgo func() {\n\t\t\tgo wrappedJob.Run()\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t\tgo wrappedJob.Run()\n\t\t}()\n\t\ttime.Sleep(3 * time.Millisecond) // Give both jobs 3ms to complete.\n\t\tif c := j.Done(); c != 2 {\n\t\t\tt.Errorf(\"expected job run twice, immediately, got %d\", c)\n\t\t}\n\t})\n\n\tt.Run(\"second run skipped if first not done\", func(t *testing.T) {\n\t\tvar j countJob\n\t\tj.delay = 10 * time.Millisecond\n\t\twrappedJob := NewChain(SkipIfStillRunning(DiscardLogger)).Then(&j)\n\t\tgo func() {\n\t\t\tgo wrappedJob.Run()\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t\tgo wrappedJob.Run()\n\t\t}()\n\n\t\t// After 5ms, the first job is still in progress, and the second job was\n\t\t// aleady skipped.\n\t\ttime.Sleep(5 * time.Millisecond)\n\t\tstarted, done := j.Started(), j.Done()\n\t\tif started != 1 || done != 0 {\n\t\t\tt.Error(\"expected first job started, but not finished, got\", started, done)\n\t\t}\n\n\t\t// Verify that the first job completes and second does not run.\n\t\ttime.Sleep(25 * time.Millisecond)\n\t\tstarted, done = j.Started(), j.Done()\n\t\tif started != 1 || done != 1 {\n\t\t\tt.Error(\"expected second job skipped, got\", started, done)\n\t\t}\n\t})\n\n\tt.Run(\"skip 10 jobs on rapid fire\", func(t *testing.T) {\n\t\tvar j countJob\n\t\tj.delay = 10 * time.Millisecond\n\t\twrappedJob := NewChain(SkipIfStillRunning(DiscardLogger)).Then(&j)\n\t\tfor i := 0; i < 11; i++ {\n\t\t\tgo wrappedJob.Run()\n\t\t}\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\tdone := j.Done()\n\t\tif done != 1 {\n\t\t\tt.Error(\"expected 1 jobs executed, 10 jobs dropped, got\", done)\n\t\t}\n\t})\n\n\tt.Run(\"different jobs independent\", func(t *testing.T) {\n\t\tvar j1, j2 countJob\n\t\tj1.delay = 10 * time.Millisecond\n\t\tj2.delay = 10 * time.Millisecond\n\t\tchain := NewChain(SkipIfStillRunning(DiscardLogger))\n\t\twrappedJob1 := chain.Then(&j1)\n\t\twrappedJob2 := chain.Then(&j2)\n\t\tfor i := 0; i < 11; i++ {\n\t\t\tgo wrappedJob1.Run()\n\t\t\tgo wrappedJob2.Run()\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tvar (\n\t\t\tdone1 = j1.Done()\n\t\t\tdone2 = j2.Done()\n\t\t)\n\t\tif done1 != 1 || done2 != 1 {\n\t\t\tt.Error(\"expected both jobs executed once, got\", done1, \"and\", done2)\n\t\t}\n\t})\n\n}\n"
  },
  {
    "path": "constantdelay.go",
    "content": "package cron\n\nimport \"time\"\n\n// ConstantDelaySchedule represents a simple recurring duty cycle, e.g. \"Every 5 minutes\".\n// It does not support jobs more frequent than once a second.\ntype ConstantDelaySchedule struct {\n\tDelay time.Duration\n}\n\n// Every returns a crontab Schedule that activates once every duration.\n// Delays of less than a second are not supported (will round up to 1 second).\n// Any fields less than a Second are truncated.\nfunc Every(duration time.Duration) ConstantDelaySchedule {\n\tif duration < time.Second {\n\t\tduration = time.Second\n\t}\n\treturn ConstantDelaySchedule{\n\t\tDelay: duration - time.Duration(duration.Nanoseconds())%time.Second,\n\t}\n}\n\n// Next returns the next time this should be run.\n// This rounds so that the next activation time will be on the second.\nfunc (schedule ConstantDelaySchedule) Next(t time.Time) time.Time {\n\treturn t.Add(schedule.Delay - time.Duration(t.Nanosecond())*time.Nanosecond)\n}\n"
  },
  {
    "path": "constantdelay_test.go",
    "content": "package cron\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestConstantDelayNext(t *testing.T) {\n\ttests := []struct {\n\t\ttime     string\n\t\tdelay    time.Duration\n\t\texpected string\n\t}{\n\t\t// Simple cases\n\t\t{\"Mon Jul 9 14:45 2012\", 15*time.Minute + 50*time.Nanosecond, \"Mon Jul 9 15:00 2012\"},\n\t\t{\"Mon Jul 9 14:59 2012\", 15 * time.Minute, \"Mon Jul 9 15:14 2012\"},\n\t\t{\"Mon Jul 9 14:59:59 2012\", 15 * time.Minute, \"Mon Jul 9 15:14:59 2012\"},\n\n\t\t// Wrap around hours\n\t\t{\"Mon Jul 9 15:45 2012\", 35 * time.Minute, \"Mon Jul 9 16:20 2012\"},\n\n\t\t// Wrap around days\n\t\t{\"Mon Jul 9 23:46 2012\", 14 * time.Minute, \"Tue Jul 10 00:00 2012\"},\n\t\t{\"Mon Jul 9 23:45 2012\", 35 * time.Minute, \"Tue Jul 10 00:20 2012\"},\n\t\t{\"Mon Jul 9 23:35:51 2012\", 44*time.Minute + 24*time.Second, \"Tue Jul 10 00:20:15 2012\"},\n\t\t{\"Mon Jul 9 23:35:51 2012\", 25*time.Hour + 44*time.Minute + 24*time.Second, \"Thu Jul 11 01:20:15 2012\"},\n\n\t\t// Wrap around months\n\t\t{\"Mon Jul 9 23:35 2012\", 91*24*time.Hour + 25*time.Minute, \"Thu Oct 9 00:00 2012\"},\n\n\t\t// Wrap around minute, hour, day, month, and year\n\t\t{\"Mon Dec 31 23:59:45 2012\", 15 * time.Second, \"Tue Jan 1 00:00:00 2013\"},\n\n\t\t// Round to nearest second on the delay\n\t\t{\"Mon Jul 9 14:45 2012\", 15*time.Minute + 50*time.Nanosecond, \"Mon Jul 9 15:00 2012\"},\n\n\t\t// Round up to 1 second if the duration is less.\n\t\t{\"Mon Jul 9 14:45:00 2012\", 15 * time.Millisecond, \"Mon Jul 9 14:45:01 2012\"},\n\n\t\t// Round to nearest second when calculating the next time.\n\t\t{\"Mon Jul 9 14:45:00.005 2012\", 15 * time.Minute, \"Mon Jul 9 15:00 2012\"},\n\n\t\t// Round to nearest second for both.\n\t\t{\"Mon Jul 9 14:45:00.005 2012\", 15*time.Minute + 50*time.Nanosecond, \"Mon Jul 9 15:00 2012\"},\n\t}\n\n\tfor _, c := range tests {\n\t\tactual := Every(c.delay).Next(getTime(c.time))\n\t\texpected := getTime(c.expected)\n\t\tif actual != expected {\n\t\t\tt.Errorf(\"%s, \\\"%s\\\": (expected) %v != %v (actual)\", c.time, c.delay, expected, actual)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "cron.go",
    "content": "package cron\n\nimport (\n\t\"context\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n)\n\n// Cron keeps track of any number of entries, invoking the associated func as\n// specified by the schedule. It may be started, stopped, and the entries may\n// be inspected while running.\ntype Cron struct {\n\tentries   []*Entry\n\tchain     Chain\n\tstop      chan struct{}\n\tadd       chan *Entry\n\tremove    chan EntryID\n\tsnapshot  chan chan []Entry\n\trunning   bool\n\tlogger    Logger\n\trunningMu sync.Mutex\n\tlocation  *time.Location\n\tparser    ScheduleParser\n\tnextID    EntryID\n\tjobWaiter sync.WaitGroup\n}\n\n// ScheduleParser is an interface for schedule spec parsers that return a Schedule\ntype ScheduleParser interface {\n\tParse(spec string) (Schedule, error)\n}\n\n// Job is an interface for submitted cron jobs.\ntype Job interface {\n\tRun()\n}\n\n// Schedule describes a job's duty cycle.\ntype Schedule interface {\n\t// Next returns the next activation time, later than the given time.\n\t// Next is invoked initially, and then each time the job is run.\n\tNext(time.Time) time.Time\n}\n\n// EntryID identifies an entry within a Cron instance\ntype EntryID int\n\n// Entry consists of a schedule and the func to execute on that schedule.\ntype Entry struct {\n\t// ID is the cron-assigned ID of this entry, which may be used to look up a\n\t// snapshot or remove it.\n\tID EntryID\n\n\t// Schedule on which this job should be run.\n\tSchedule Schedule\n\n\t// Next time the job will run, or the zero time if Cron has not been\n\t// started or this entry's schedule is unsatisfiable\n\tNext time.Time\n\n\t// Prev is the last time this job was run, or the zero time if never.\n\tPrev time.Time\n\n\t// WrappedJob is the thing to run when the Schedule is activated.\n\tWrappedJob Job\n\n\t// Job is the thing that was submitted to cron.\n\t// It is kept around so that user code that needs to get at the job later,\n\t// e.g. via Entries() can do so.\n\tJob Job\n}\n\n// Valid returns true if this is not the zero entry.\nfunc (e Entry) Valid() bool { return e.ID != 0 }\n\n// byTime is a wrapper for sorting the entry array by time\n// (with zero time at the end).\ntype byTime []*Entry\n\nfunc (s byTime) Len() int      { return len(s) }\nfunc (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s byTime) Less(i, j int) bool {\n\t// Two zero times should return false.\n\t// Otherwise, zero is \"greater\" than any other time.\n\t// (To sort it at the end of the list.)\n\tif s[i].Next.IsZero() {\n\t\treturn false\n\t}\n\tif s[j].Next.IsZero() {\n\t\treturn true\n\t}\n\treturn s[i].Next.Before(s[j].Next)\n}\n\n// New returns a new Cron job runner, modified by the given options.\n//\n// Available Settings\n//\n//   Time Zone\n//     Description: The time zone in which schedules are interpreted\n//     Default:     time.Local\n//\n//   Parser\n//     Description: Parser converts cron spec strings into cron.Schedules.\n//     Default:     Accepts this spec: https://en.wikipedia.org/wiki/Cron\n//\n//   Chain\n//     Description: Wrap submitted jobs to customize behavior.\n//     Default:     A chain that recovers panics and logs them to stderr.\n//\n// See \"cron.With*\" to modify the default behavior.\nfunc New(opts ...Option) *Cron {\n\tc := &Cron{\n\t\tentries:   nil,\n\t\tchain:     NewChain(),\n\t\tadd:       make(chan *Entry),\n\t\tstop:      make(chan struct{}),\n\t\tsnapshot:  make(chan chan []Entry),\n\t\tremove:    make(chan EntryID),\n\t\trunning:   false,\n\t\trunningMu: sync.Mutex{},\n\t\tlogger:    DefaultLogger,\n\t\tlocation:  time.Local,\n\t\tparser:    standardParser,\n\t}\n\tfor _, opt := range opts {\n\t\topt(c)\n\t}\n\treturn c\n}\n\n// FuncJob is a wrapper that turns a func() into a cron.Job\ntype FuncJob func()\n\nfunc (f FuncJob) Run() { f() }\n\n// AddFunc adds a func to the Cron to be run on the given schedule.\n// The spec is parsed using the time zone of this Cron instance as the default.\n// An opaque ID is returned that can be used to later remove it.\nfunc (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) {\n\treturn c.AddJob(spec, FuncJob(cmd))\n}\n\n// AddJob adds a Job to the Cron to be run on the given schedule.\n// The spec is parsed using the time zone of this Cron instance as the default.\n// An opaque ID is returned that can be used to later remove it.\nfunc (c *Cron) AddJob(spec string, cmd Job) (EntryID, error) {\n\tschedule, err := c.parser.Parse(spec)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn c.Schedule(schedule, cmd), nil\n}\n\n// Schedule adds a Job to the Cron to be run on the given schedule.\n// The job is wrapped with the configured Chain.\nfunc (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID {\n\tc.runningMu.Lock()\n\tdefer c.runningMu.Unlock()\n\tc.nextID++\n\tentry := &Entry{\n\t\tID:         c.nextID,\n\t\tSchedule:   schedule,\n\t\tWrappedJob: c.chain.Then(cmd),\n\t\tJob:        cmd,\n\t}\n\tif !c.running {\n\t\tc.entries = append(c.entries, entry)\n\t} else {\n\t\tc.add <- entry\n\t}\n\treturn entry.ID\n}\n\n// Entries returns a snapshot of the cron entries.\nfunc (c *Cron) Entries() []Entry {\n\tc.runningMu.Lock()\n\tdefer c.runningMu.Unlock()\n\tif c.running {\n\t\treplyChan := make(chan []Entry, 1)\n\t\tc.snapshot <- replyChan\n\t\treturn <-replyChan\n\t}\n\treturn c.entrySnapshot()\n}\n\n// Location gets the time zone location\nfunc (c *Cron) Location() *time.Location {\n\treturn c.location\n}\n\n// Entry returns a snapshot of the given entry, or nil if it couldn't be found.\nfunc (c *Cron) Entry(id EntryID) Entry {\n\tfor _, entry := range c.Entries() {\n\t\tif id == entry.ID {\n\t\t\treturn entry\n\t\t}\n\t}\n\treturn Entry{}\n}\n\n// Remove an entry from being run in the future.\nfunc (c *Cron) Remove(id EntryID) {\n\tc.runningMu.Lock()\n\tdefer c.runningMu.Unlock()\n\tif c.running {\n\t\tc.remove <- id\n\t} else {\n\t\tc.removeEntry(id)\n\t}\n}\n\n// Start the cron scheduler in its own goroutine, or no-op if already started.\nfunc (c *Cron) Start() {\n\tc.runningMu.Lock()\n\tdefer c.runningMu.Unlock()\n\tif c.running {\n\t\treturn\n\t}\n\tc.running = true\n\tgo c.run()\n}\n\n// Run the cron scheduler, or no-op if already running.\nfunc (c *Cron) Run() {\n\tc.runningMu.Lock()\n\tif c.running {\n\t\tc.runningMu.Unlock()\n\t\treturn\n\t}\n\tc.running = true\n\tc.runningMu.Unlock()\n\tc.run()\n}\n\n// run the scheduler.. this is private just due to the need to synchronize\n// access to the 'running' state variable.\nfunc (c *Cron) run() {\n\tc.logger.Info(\"start\")\n\n\t// Figure out the next activation times for each entry.\n\tnow := c.now()\n\tfor _, entry := range c.entries {\n\t\tentry.Next = entry.Schedule.Next(now)\n\t\tc.logger.Info(\"schedule\", \"now\", now, \"entry\", entry.ID, \"next\", entry.Next)\n\t}\n\n\tfor {\n\t\t// Determine the next entry to run.\n\t\tsort.Sort(byTime(c.entries))\n\n\t\tvar timer *time.Timer\n\t\tif len(c.entries) == 0 || c.entries[0].Next.IsZero() {\n\t\t\t// If there are no entries yet, just sleep - it still handles new entries\n\t\t\t// and stop requests.\n\t\t\ttimer = time.NewTimer(100000 * time.Hour)\n\t\t} else {\n\t\t\ttimer = time.NewTimer(c.entries[0].Next.Sub(now))\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase now = <-timer.C:\n\t\t\t\tnow = now.In(c.location)\n\t\t\t\tc.logger.Info(\"wake\", \"now\", now)\n\n\t\t\t\t// Run every entry whose next time was less than now\n\t\t\t\tfor _, e := range c.entries {\n\t\t\t\t\tif e.Next.After(now) || e.Next.IsZero() {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tc.startJob(e.WrappedJob)\n\t\t\t\t\te.Prev = e.Next\n\t\t\t\t\te.Next = e.Schedule.Next(now)\n\t\t\t\t\tc.logger.Info(\"run\", \"now\", now, \"entry\", e.ID, \"next\", e.Next)\n\t\t\t\t}\n\n\t\t\tcase newEntry := <-c.add:\n\t\t\t\ttimer.Stop()\n\t\t\t\tnow = c.now()\n\t\t\t\tnewEntry.Next = newEntry.Schedule.Next(now)\n\t\t\t\tc.entries = append(c.entries, newEntry)\n\t\t\t\tc.logger.Info(\"added\", \"now\", now, \"entry\", newEntry.ID, \"next\", newEntry.Next)\n\n\t\t\tcase replyChan := <-c.snapshot:\n\t\t\t\treplyChan <- c.entrySnapshot()\n\t\t\t\tcontinue\n\n\t\t\tcase <-c.stop:\n\t\t\t\ttimer.Stop()\n\t\t\t\tc.logger.Info(\"stop\")\n\t\t\t\treturn\n\n\t\t\tcase id := <-c.remove:\n\t\t\t\ttimer.Stop()\n\t\t\t\tnow = c.now()\n\t\t\t\tc.removeEntry(id)\n\t\t\t\tc.logger.Info(\"removed\", \"entry\", id)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n// startJob runs the given job in a new goroutine.\nfunc (c *Cron) startJob(j Job) {\n\tc.jobWaiter.Add(1)\n\tgo func() {\n\t\tdefer c.jobWaiter.Done()\n\t\tj.Run()\n\t}()\n}\n\n// now returns current time in c location\nfunc (c *Cron) now() time.Time {\n\treturn time.Now().In(c.location)\n}\n\n// Stop stops the cron scheduler if it is running; otherwise it does nothing.\n// A context is returned so the caller can wait for running jobs to complete.\nfunc (c *Cron) Stop() context.Context {\n\tc.runningMu.Lock()\n\tdefer c.runningMu.Unlock()\n\tif c.running {\n\t\tc.stop <- struct{}{}\n\t\tc.running = false\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tc.jobWaiter.Wait()\n\t\tcancel()\n\t}()\n\treturn ctx\n}\n\n// entrySnapshot returns a copy of the current cron entry list.\nfunc (c *Cron) entrySnapshot() []Entry {\n\tvar entries = make([]Entry, len(c.entries))\n\tfor i, e := range c.entries {\n\t\tentries[i] = *e\n\t}\n\treturn entries\n}\n\nfunc (c *Cron) removeEntry(id EntryID) {\n\tvar entries []*Entry\n\tfor _, e := range c.entries {\n\t\tif e.ID != id {\n\t\t\tentries = append(entries, e)\n\t\t}\n\t}\n\tc.entries = entries\n}\n"
  },
  {
    "path": "cron_test.go",
    "content": "package cron\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\n// Many tests schedule a job for every second, and then wait at most a second\n// for it to run.  This amount is just slightly larger than 1 second to\n// compensate for a few milliseconds of runtime.\nconst OneSecond = 1*time.Second + 50*time.Millisecond\n\ntype syncWriter struct {\n\twr bytes.Buffer\n\tm  sync.Mutex\n}\n\nfunc (sw *syncWriter) Write(data []byte) (n int, err error) {\n\tsw.m.Lock()\n\tn, err = sw.wr.Write(data)\n\tsw.m.Unlock()\n\treturn\n}\n\nfunc (sw *syncWriter) String() string {\n\tsw.m.Lock()\n\tdefer sw.m.Unlock()\n\treturn sw.wr.String()\n}\n\nfunc newBufLogger(sw *syncWriter) Logger {\n\treturn PrintfLogger(log.New(sw, \"\", log.LstdFlags))\n}\n\nfunc TestFuncPanicRecovery(t *testing.T) {\n\tvar buf syncWriter\n\tcron := New(WithParser(secondParser),\n\t\tWithChain(Recover(newBufLogger(&buf))))\n\tcron.Start()\n\tdefer cron.Stop()\n\tcron.AddFunc(\"* * * * * ?\", func() {\n\t\tpanic(\"YOLO\")\n\t})\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tif !strings.Contains(buf.String(), \"YOLO\") {\n\t\t\tt.Error(\"expected a panic to be logged, got none\")\n\t\t}\n\t\treturn\n\t}\n}\n\ntype DummyJob struct{}\n\nfunc (d DummyJob) Run() {\n\tpanic(\"YOLO\")\n}\n\nfunc TestJobPanicRecovery(t *testing.T) {\n\tvar job DummyJob\n\n\tvar buf syncWriter\n\tcron := New(WithParser(secondParser),\n\t\tWithChain(Recover(newBufLogger(&buf))))\n\tcron.Start()\n\tdefer cron.Stop()\n\tcron.AddJob(\"* * * * * ?\", job)\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tif !strings.Contains(buf.String(), \"YOLO\") {\n\t\t\tt.Error(\"expected a panic to be logged, got none\")\n\t\t}\n\t\treturn\n\t}\n}\n\n// Start and stop cron with no entries.\nfunc TestNoEntries(t *testing.T) {\n\tcron := newWithSeconds()\n\tcron.Start()\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tt.Fatal(\"expected cron will be stopped immediately\")\n\tcase <-stop(cron):\n\t}\n}\n\n// Start, stop, then add an entry. Verify entry doesn't run.\nfunc TestStopCausesJobsToNotRun(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\n\tcron := newWithSeconds()\n\tcron.Start()\n\tcron.Stop()\n\tcron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\t// No job ran!\n\tcase <-wait(wg):\n\t\tt.Fatal(\"expected stopped cron does not run any job\")\n\t}\n}\n\n// Add a job, start cron, expect it runs.\nfunc TestAddBeforeRunning(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\n\tcron := newWithSeconds()\n\tcron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\tcron.Start()\n\tdefer cron.Stop()\n\n\t// Give cron 2 seconds to run our job (which is always activated).\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tt.Fatal(\"expected job runs\")\n\tcase <-wait(wg):\n\t}\n}\n\n// Start cron, add a job, expect it runs.\nfunc TestAddWhileRunning(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\n\tcron := newWithSeconds()\n\tcron.Start()\n\tdefer cron.Stop()\n\tcron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tt.Fatal(\"expected job runs\")\n\tcase <-wait(wg):\n\t}\n}\n\n// Test for #34. Adding a job after calling start results in multiple job invocations\nfunc TestAddWhileRunningWithDelay(t *testing.T) {\n\tcron := newWithSeconds()\n\tcron.Start()\n\tdefer cron.Stop()\n\ttime.Sleep(5 * time.Second)\n\tvar calls int64\n\tcron.AddFunc(\"* * * * * *\", func() { atomic.AddInt64(&calls, 1) })\n\n\t<-time.After(OneSecond)\n\tif atomic.LoadInt64(&calls) != 1 {\n\t\tt.Errorf(\"called %d times, expected 1\\n\", calls)\n\t}\n}\n\n// Add a job, remove a job, start cron, expect nothing runs.\nfunc TestRemoveBeforeRunning(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\n\tcron := newWithSeconds()\n\tid, _ := cron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\tcron.Remove(id)\n\tcron.Start()\n\tdefer cron.Stop()\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\t// Success, shouldn't run\n\tcase <-wait(wg):\n\t\tt.FailNow()\n\t}\n}\n\n// Start cron, add a job, remove it, expect it doesn't run.\nfunc TestRemoveWhileRunning(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\n\tcron := newWithSeconds()\n\tcron.Start()\n\tdefer cron.Stop()\n\tid, _ := cron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\tcron.Remove(id)\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\tcase <-wait(wg):\n\t\tt.FailNow()\n\t}\n}\n\n// Test timing with Entries.\nfunc TestSnapshotEntries(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\n\tcron := New()\n\tcron.AddFunc(\"@every 2s\", func() { wg.Done() })\n\tcron.Start()\n\tdefer cron.Stop()\n\n\t// Cron should fire in 2 seconds. After 1 second, call Entries.\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tcron.Entries()\n\t}\n\n\t// Even though Entries was called, the cron should fire at the 2 second mark.\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tt.Error(\"expected job runs at 2 second mark\")\n\tcase <-wait(wg):\n\t}\n}\n\n// Test that the entries are correctly sorted.\n// Add a bunch of long-in-the-future entries, and an immediate entry, and ensure\n// that the immediate entry runs immediately.\n// Also: Test that multiple jobs run in the same instant.\nfunc TestMultipleEntries(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(2)\n\n\tcron := newWithSeconds()\n\tcron.AddFunc(\"0 0 0 1 1 ?\", func() {})\n\tcron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\tid1, _ := cron.AddFunc(\"* * * * * ?\", func() { t.Fatal() })\n\tid2, _ := cron.AddFunc(\"* * * * * ?\", func() { t.Fatal() })\n\tcron.AddFunc(\"0 0 0 31 12 ?\", func() {})\n\tcron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\n\tcron.Remove(id1)\n\tcron.Start()\n\tcron.Remove(id2)\n\tdefer cron.Stop()\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tt.Error(\"expected job run in proper order\")\n\tcase <-wait(wg):\n\t}\n}\n\n// Test running the same job twice.\nfunc TestRunningJobTwice(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(2)\n\n\tcron := newWithSeconds()\n\tcron.AddFunc(\"0 0 0 1 1 ?\", func() {})\n\tcron.AddFunc(\"0 0 0 31 12 ?\", func() {})\n\tcron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\n\tcron.Start()\n\tdefer cron.Stop()\n\n\tselect {\n\tcase <-time.After(2 * OneSecond):\n\t\tt.Error(\"expected job fires 2 times\")\n\tcase <-wait(wg):\n\t}\n}\n\nfunc TestRunningMultipleSchedules(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(2)\n\n\tcron := newWithSeconds()\n\tcron.AddFunc(\"0 0 0 1 1 ?\", func() {})\n\tcron.AddFunc(\"0 0 0 31 12 ?\", func() {})\n\tcron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\tcron.Schedule(Every(time.Minute), FuncJob(func() {}))\n\tcron.Schedule(Every(time.Second), FuncJob(func() { wg.Done() }))\n\tcron.Schedule(Every(time.Hour), FuncJob(func() {}))\n\n\tcron.Start()\n\tdefer cron.Stop()\n\n\tselect {\n\tcase <-time.After(2 * OneSecond):\n\t\tt.Error(\"expected job fires 2 times\")\n\tcase <-wait(wg):\n\t}\n}\n\n// Test that the cron is run in the local time zone (as opposed to UTC).\nfunc TestLocalTimezone(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(2)\n\n\tnow := time.Now()\n\t// FIX: Issue #205\n\t// This calculation doesn't work in seconds 58 or 59.\n\t// Take the easy way out and sleep.\n\tif now.Second() >= 58 {\n\t\ttime.Sleep(2 * time.Second)\n\t\tnow = time.Now()\n\t}\n\tspec := fmt.Sprintf(\"%d,%d %d %d %d %d ?\",\n\t\tnow.Second()+1, now.Second()+2, now.Minute(), now.Hour(), now.Day(), now.Month())\n\n\tcron := newWithSeconds()\n\tcron.AddFunc(spec, func() { wg.Done() })\n\tcron.Start()\n\tdefer cron.Stop()\n\n\tselect {\n\tcase <-time.After(OneSecond * 2):\n\t\tt.Error(\"expected job fires 2 times\")\n\tcase <-wait(wg):\n\t}\n}\n\n// Test that the cron is run in the given time zone (as opposed to local).\nfunc TestNonLocalTimezone(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(2)\n\n\tloc, err := time.LoadLocation(\"Atlantic/Cape_Verde\")\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to load time zone Atlantic/Cape_Verde: %+v\", err)\n\t\tt.Fail()\n\t}\n\n\tnow := time.Now().In(loc)\n\t// FIX: Issue #205\n\t// This calculation doesn't work in seconds 58 or 59.\n\t// Take the easy way out and sleep.\n\tif now.Second() >= 58 {\n\t\ttime.Sleep(2 * time.Second)\n\t\tnow = time.Now().In(loc)\n\t}\n\tspec := fmt.Sprintf(\"%d,%d %d %d %d %d ?\",\n\t\tnow.Second()+1, now.Second()+2, now.Minute(), now.Hour(), now.Day(), now.Month())\n\n\tcron := New(WithLocation(loc), WithParser(secondParser))\n\tcron.AddFunc(spec, func() { wg.Done() })\n\tcron.Start()\n\tdefer cron.Stop()\n\n\tselect {\n\tcase <-time.After(OneSecond * 2):\n\t\tt.Error(\"expected job fires 2 times\")\n\tcase <-wait(wg):\n\t}\n}\n\n// Test that calling stop before start silently returns without\n// blocking the stop channel.\nfunc TestStopWithoutStart(t *testing.T) {\n\tcron := New()\n\tcron.Stop()\n}\n\ntype testJob struct {\n\twg   *sync.WaitGroup\n\tname string\n}\n\nfunc (t testJob) Run() {\n\tt.wg.Done()\n}\n\n// Test that adding an invalid job spec returns an error\nfunc TestInvalidJobSpec(t *testing.T) {\n\tcron := New()\n\t_, err := cron.AddJob(\"this will not parse\", nil)\n\tif err == nil {\n\t\tt.Errorf(\"expected an error with invalid spec, got nil\")\n\t}\n}\n\n// Test blocking run method behaves as Start()\nfunc TestBlockingRun(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\n\tcron := newWithSeconds()\n\tcron.AddFunc(\"* * * * * ?\", func() { wg.Done() })\n\n\tvar unblockChan = make(chan struct{})\n\n\tgo func() {\n\t\tcron.Run()\n\t\tclose(unblockChan)\n\t}()\n\tdefer cron.Stop()\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tt.Error(\"expected job fires\")\n\tcase <-unblockChan:\n\t\tt.Error(\"expected that Run() blocks\")\n\tcase <-wait(wg):\n\t}\n}\n\n// Test that double-running is a no-op\nfunc TestStartNoop(t *testing.T) {\n\tvar tickChan = make(chan struct{}, 2)\n\n\tcron := newWithSeconds()\n\tcron.AddFunc(\"* * * * * ?\", func() {\n\t\ttickChan <- struct{}{}\n\t})\n\n\tcron.Start()\n\tdefer cron.Stop()\n\n\t// Wait for the first firing to ensure the runner is going\n\t<-tickChan\n\n\tcron.Start()\n\n\t<-tickChan\n\n\t// Fail if this job fires again in a short period, indicating a double-run\n\tselect {\n\tcase <-time.After(time.Millisecond):\n\tcase <-tickChan:\n\t\tt.Error(\"expected job fires exactly twice\")\n\t}\n}\n\n// Simple test using Runnables.\nfunc TestJob(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\n\tcron := newWithSeconds()\n\tcron.AddJob(\"0 0 0 30 Feb ?\", testJob{wg, \"job0\"})\n\tcron.AddJob(\"0 0 0 1 1 ?\", testJob{wg, \"job1\"})\n\tjob2, _ := cron.AddJob(\"* * * * * ?\", testJob{wg, \"job2\"})\n\tcron.AddJob(\"1 0 0 1 1 ?\", testJob{wg, \"job3\"})\n\tcron.Schedule(Every(5*time.Second+5*time.Nanosecond), testJob{wg, \"job4\"})\n\tjob5 := cron.Schedule(Every(5*time.Minute), testJob{wg, \"job5\"})\n\n\t// Test getting an Entry pre-Start.\n\tif actualName := cron.Entry(job2).Job.(testJob).name; actualName != \"job2\" {\n\t\tt.Error(\"wrong job retrieved:\", actualName)\n\t}\n\tif actualName := cron.Entry(job5).Job.(testJob).name; actualName != \"job5\" {\n\t\tt.Error(\"wrong job retrieved:\", actualName)\n\t}\n\n\tcron.Start()\n\tdefer cron.Stop()\n\n\tselect {\n\tcase <-time.After(OneSecond):\n\t\tt.FailNow()\n\tcase <-wait(wg):\n\t}\n\n\t// Ensure the entries are in the right order.\n\texpecteds := []string{\"job2\", \"job4\", \"job5\", \"job1\", \"job3\", \"job0\"}\n\n\tvar actuals []string\n\tfor _, entry := range cron.Entries() {\n\t\tactuals = append(actuals, entry.Job.(testJob).name)\n\t}\n\n\tfor i, expected := range expecteds {\n\t\tif actuals[i] != expected {\n\t\t\tt.Fatalf(\"Jobs not in the right order.  (expected) %s != %s (actual)\", expecteds, actuals)\n\t\t}\n\t}\n\n\t// Test getting Entries.\n\tif actualName := cron.Entry(job2).Job.(testJob).name; actualName != \"job2\" {\n\t\tt.Error(\"wrong job retrieved:\", actualName)\n\t}\n\tif actualName := cron.Entry(job5).Job.(testJob).name; actualName != \"job5\" {\n\t\tt.Error(\"wrong job retrieved:\", actualName)\n\t}\n}\n\n// Issue #206\n// Ensure that the next run of a job after removing an entry is accurate.\nfunc TestScheduleAfterRemoval(t *testing.T) {\n\tvar wg1 sync.WaitGroup\n\tvar wg2 sync.WaitGroup\n\twg1.Add(1)\n\twg2.Add(1)\n\n\t// The first time this job is run, set a timer and remove the other job\n\t// 750ms later. Correct behavior would be to still run the job again in\n\t// 250ms, but the bug would cause it to run instead 1s later.\n\n\tvar calls int\n\tvar mu sync.Mutex\n\n\tcron := newWithSeconds()\n\thourJob := cron.Schedule(Every(time.Hour), FuncJob(func() {}))\n\tcron.Schedule(Every(time.Second), FuncJob(func() {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\tswitch calls {\n\t\tcase 0:\n\t\t\twg1.Done()\n\t\t\tcalls++\n\t\tcase 1:\n\t\t\ttime.Sleep(750 * time.Millisecond)\n\t\t\tcron.Remove(hourJob)\n\t\t\tcalls++\n\t\tcase 2:\n\t\t\tcalls++\n\t\t\twg2.Done()\n\t\tcase 3:\n\t\t\tpanic(\"unexpected 3rd call\")\n\t\t}\n\t}))\n\n\tcron.Start()\n\tdefer cron.Stop()\n\n\t// the first run might be any length of time 0 - 1s, since the schedule\n\t// rounds to the second. wait for the first run to true up.\n\twg1.Wait()\n\n\tselect {\n\tcase <-time.After(2 * OneSecond):\n\t\tt.Error(\"expected job fires 2 times\")\n\tcase <-wait(&wg2):\n\t}\n}\n\ntype ZeroSchedule struct{}\n\nfunc (*ZeroSchedule) Next(time.Time) time.Time {\n\treturn time.Time{}\n}\n\n// Tests that job without time does not run\nfunc TestJobWithZeroTimeDoesNotRun(t *testing.T) {\n\tcron := newWithSeconds()\n\tvar calls int64\n\tcron.AddFunc(\"* * * * * *\", func() { atomic.AddInt64(&calls, 1) })\n\tcron.Schedule(new(ZeroSchedule), FuncJob(func() { t.Error(\"expected zero task will not run\") }))\n\tcron.Start()\n\tdefer cron.Stop()\n\t<-time.After(OneSecond)\n\tif atomic.LoadInt64(&calls) != 1 {\n\t\tt.Errorf(\"called %d times, expected 1\\n\", calls)\n\t}\n}\n\nfunc TestStopAndWait(t *testing.T) {\n\tt.Run(\"nothing running, returns immediately\", func(t *testing.T) {\n\t\tcron := newWithSeconds()\n\t\tcron.Start()\n\t\tctx := cron.Stop()\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase <-time.After(time.Millisecond):\n\t\t\tt.Error(\"context was not done immediately\")\n\t\t}\n\t})\n\n\tt.Run(\"repeated calls to Stop\", func(t *testing.T) {\n\t\tcron := newWithSeconds()\n\t\tcron.Start()\n\t\t_ = cron.Stop()\n\t\ttime.Sleep(time.Millisecond)\n\t\tctx := cron.Stop()\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase <-time.After(time.Millisecond):\n\t\t\tt.Error(\"context was not done immediately\")\n\t\t}\n\t})\n\n\tt.Run(\"a couple fast jobs added, still returns immediately\", func(t *testing.T) {\n\t\tcron := newWithSeconds()\n\t\tcron.AddFunc(\"* * * * * *\", func() {})\n\t\tcron.Start()\n\t\tcron.AddFunc(\"* * * * * *\", func() {})\n\t\tcron.AddFunc(\"* * * * * *\", func() {})\n\t\tcron.AddFunc(\"* * * * * *\", func() {})\n\t\ttime.Sleep(time.Second)\n\t\tctx := cron.Stop()\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase <-time.After(time.Millisecond):\n\t\t\tt.Error(\"context was not done immediately\")\n\t\t}\n\t})\n\n\tt.Run(\"a couple fast jobs and a slow job added, waits for slow job\", func(t *testing.T) {\n\t\tcron := newWithSeconds()\n\t\tcron.AddFunc(\"* * * * * *\", func() {})\n\t\tcron.Start()\n\t\tcron.AddFunc(\"* * * * * *\", func() { time.Sleep(2 * time.Second) })\n\t\tcron.AddFunc(\"* * * * * *\", func() {})\n\t\ttime.Sleep(time.Second)\n\n\t\tctx := cron.Stop()\n\n\t\t// Verify that it is not done for at least 750ms\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tt.Error(\"context was done too quickly immediately\")\n\t\tcase <-time.After(750 * time.Millisecond):\n\t\t\t// expected, because the job sleeping for 1 second is still running\n\t\t}\n\n\t\t// Verify that it IS done in the next 500ms (giving 250ms buffer)\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\t// expected\n\t\tcase <-time.After(1500 * time.Millisecond):\n\t\t\tt.Error(\"context not done after job should have completed\")\n\t\t}\n\t})\n\n\tt.Run(\"repeated calls to stop, waiting for completion and after\", func(t *testing.T) {\n\t\tcron := newWithSeconds()\n\t\tcron.AddFunc(\"* * * * * *\", func() {})\n\t\tcron.AddFunc(\"* * * * * *\", func() { time.Sleep(2 * time.Second) })\n\t\tcron.Start()\n\t\tcron.AddFunc(\"* * * * * *\", func() {})\n\t\ttime.Sleep(time.Second)\n\t\tctx := cron.Stop()\n\t\tctx2 := cron.Stop()\n\n\t\t// Verify that it is not done for at least 1500ms\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tt.Error(\"context was done too quickly immediately\")\n\t\tcase <-ctx2.Done():\n\t\t\tt.Error(\"context2 was done too quickly immediately\")\n\t\tcase <-time.After(1500 * time.Millisecond):\n\t\t\t// expected, because the job sleeping for 2 seconds is still running\n\t\t}\n\n\t\t// Verify that it IS done in the next 1s (giving 500ms buffer)\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\t// expected\n\t\tcase <-time.After(time.Second):\n\t\t\tt.Error(\"context not done after job should have completed\")\n\t\t}\n\n\t\t// Verify that ctx2 is also done.\n\t\tselect {\n\t\tcase <-ctx2.Done():\n\t\t\t// expected\n\t\tcase <-time.After(time.Millisecond):\n\t\t\tt.Error(\"context2 not done even though context1 is\")\n\t\t}\n\n\t\t// Verify that a new context retrieved from stop is immediately done.\n\t\tctx3 := cron.Stop()\n\t\tselect {\n\t\tcase <-ctx3.Done():\n\t\t\t// expected\n\t\tcase <-time.After(time.Millisecond):\n\t\t\tt.Error(\"context not done even when cron Stop is completed\")\n\t\t}\n\n\t})\n}\n\nfunc TestMultiThreadedStartAndStop(t *testing.T) {\n\tcron := New()\n\tgo cron.Run()\n\ttime.Sleep(2 * time.Millisecond)\n\tcron.Stop()\n}\n\nfunc wait(wg *sync.WaitGroup) chan bool {\n\tch := make(chan bool)\n\tgo func() {\n\t\twg.Wait()\n\t\tch <- true\n\t}()\n\treturn ch\n}\n\nfunc stop(cron *Cron) chan bool {\n\tch := make(chan bool)\n\tgo func() {\n\t\tcron.Stop()\n\t\tch <- true\n\t}()\n\treturn ch\n}\n\n// newWithSeconds returns a Cron with the seconds field enabled.\nfunc newWithSeconds() *Cron {\n\treturn New(WithParser(secondParser), WithChain())\n}\n"
  },
  {
    "path": "doc.go",
    "content": "/*\nPackage cron implements a cron spec parser and job runner.\n\nInstallation\n\nTo download the specific tagged release, run:\n\n\tgo get github.com/robfig/cron/v3@v3.0.0\n\nImport it in your program as:\n\n\timport \"github.com/robfig/cron/v3\"\n\nIt requires Go 1.11 or later due to usage of Go Modules.\n\nUsage\n\nCallers may register Funcs to be invoked on a given schedule.  Cron will run\nthem in their own goroutines.\n\n\tc := cron.New()\n\tc.AddFunc(\"30 * * * *\", func() { fmt.Println(\"Every hour on the half hour\") })\n\tc.AddFunc(\"30 3-6,20-23 * * *\", func() { fmt.Println(\".. in the range 3-6am, 8-11pm\") })\n\tc.AddFunc(\"CRON_TZ=Asia/Tokyo 30 04 * * *\", func() { fmt.Println(\"Runs at 04:30 Tokyo time every day\") })\n\tc.AddFunc(\"@hourly\",      func() { fmt.Println(\"Every hour, starting an hour from now\") })\n\tc.AddFunc(\"@every 1h30m\", func() { fmt.Println(\"Every hour thirty, starting an hour thirty from now\") })\n\tc.Start()\n\t..\n\t// Funcs are invoked in their own goroutine, asynchronously.\n\t...\n\t// Funcs may also be added to a running Cron\n\tc.AddFunc(\"@daily\", func() { fmt.Println(\"Every day\") })\n\t..\n\t// Inspect the cron job entries' next and previous run times.\n\tinspect(c.Entries())\n\t..\n\tc.Stop()  // Stop the scheduler (does not stop any jobs already running).\n\nCRON Expression Format\n\nA cron expression represents a set of times, using 5 space-separated fields.\n\n\tField name   | Mandatory? | Allowed values  | Allowed special characters\n\t----------   | ---------- | --------------  | --------------------------\n\tMinutes      | Yes        | 0-59            | * / , -\n\tHours        | Yes        | 0-23            | * / , -\n\tDay of month | Yes        | 1-31            | * / , - ?\n\tMonth        | Yes        | 1-12 or JAN-DEC | * / , -\n\tDay of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?\n\nMonth and Day-of-week field values are case insensitive.  \"SUN\", \"Sun\", and\n\"sun\" are equally accepted.\n\nThe specific interpretation of the format is based on the Cron Wikipedia page:\nhttps://en.wikipedia.org/wiki/Cron\n\nAlternative Formats\n\nAlternative Cron expression formats support other fields like seconds. You can\nimplement that by creating a custom Parser as follows.\n\n\tcron.New(\n\t\tcron.WithParser(\n\t\t\tcron.NewParser(\n\t\t\t\tcron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)))\n\nSince adding Seconds is the most common modification to the standard cron spec,\ncron provides a builtin function to do that, which is equivalent to the custom\nparser you saw earlier, except that its seconds field is REQUIRED:\n\n\tcron.New(cron.WithSeconds())\n\nThat emulates Quartz, the most popular alternative Cron schedule format:\nhttp://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html\n\nSpecial Characters\n\nAsterisk ( * )\n\nThe asterisk indicates that the cron expression will match for all values of the\nfield; e.g., using an asterisk in the 5th field (month) would indicate every\nmonth.\n\nSlash ( / )\n\nSlashes are used to describe increments of ranges. For example 3-59/15 in the\n1st field (minutes) would indicate the 3rd minute of the hour and every 15\nminutes thereafter. The form \"*\\/...\" is equivalent to the form \"first-last/...\",\nthat is, an increment over the largest possible range of the field.  The form\n\"N/...\" is accepted as meaning \"N-MAX/...\", that is, starting at N, use the\nincrement until the end of that specific range.  It does not wrap around.\n\nComma ( , )\n\nCommas are used to separate items of a list. For example, using \"MON,WED,FRI\" in\nthe 5th field (day of week) would mean Mondays, Wednesdays and Fridays.\n\nHyphen ( - )\n\nHyphens are used to define ranges. For example, 9-17 would indicate every\nhour between 9am and 5pm inclusive.\n\nQuestion mark ( ? )\n\nQuestion mark may be used instead of '*' for leaving either day-of-month or\nday-of-week blank.\n\nPredefined schedules\n\nYou may use one of several pre-defined schedules in place of a cron expression.\n\n\tEntry                  | Description                                | Equivalent To\n\t-----                  | -----------                                | -------------\n\t@yearly (or @annually) | Run once a year, midnight, Jan. 1st        | 0 0 1 1 *\n\t@monthly               | Run once a month, midnight, first of month | 0 0 1 * *\n\t@weekly                | Run once a week, midnight between Sat/Sun  | 0 0 * * 0\n\t@daily (or @midnight)  | Run once a day, midnight                   | 0 0 * * *\n\t@hourly                | Run once an hour, beginning of hour        | 0 * * * *\n\nIntervals\n\nYou may also schedule a job to execute at fixed intervals, starting at the time it's added\nor cron is run. This is supported by formatting the cron spec like this:\n\n    @every <duration>\n\nwhere \"duration\" is a string accepted by time.ParseDuration\n(http://golang.org/pkg/time/#ParseDuration).\n\nFor example, \"@every 1h30m10s\" would indicate a schedule that activates after\n1 hour, 30 minutes, 10 seconds, and then every interval after that.\n\nNote: The interval does not take the job runtime into account.  For example,\nif a job takes 3 minutes to run, and it is scheduled to run every 5 minutes,\nit will have only 2 minutes of idle time between each run.\n\nTime zones\n\nBy default, all interpretation and scheduling is done in the machine's local\ntime zone (time.Local). You can specify a different time zone on construction:\n\n      cron.New(\n          cron.WithLocation(time.UTC))\n\nIndividual cron schedules may also override the time zone they are to be\ninterpreted in by providing an additional space-separated field at the beginning\nof the cron spec, of the form \"CRON_TZ=Asia/Tokyo\".\n\nFor example:\n\n\t# Runs at 6am in time.Local\n\tcron.New().AddFunc(\"0 6 * * ?\", ...)\n\n\t# Runs at 6am in America/New_York\n\tnyc, _ := time.LoadLocation(\"America/New_York\")\n\tc := cron.New(cron.WithLocation(nyc))\n\tc.AddFunc(\"0 6 * * ?\", ...)\n\n\t# Runs at 6am in Asia/Tokyo\n\tcron.New().AddFunc(\"CRON_TZ=Asia/Tokyo 0 6 * * ?\", ...)\n\n\t# Runs at 6am in Asia/Tokyo\n\tc := cron.New(cron.WithLocation(nyc))\n\tc.SetLocation(\"America/New_York\")\n\tc.AddFunc(\"CRON_TZ=Asia/Tokyo 0 6 * * ?\", ...)\n\nThe prefix \"TZ=(TIME ZONE)\" is also supported for legacy compatibility.\n\nBe aware that jobs scheduled during daylight-savings leap-ahead transitions will\nnot be run!\n\nJob Wrappers\n\nA Cron runner may be configured with a chain of job wrappers to add\ncross-cutting functionality to all submitted jobs. For example, they may be used\nto achieve the following effects:\n\n  - Recover any panics from jobs (activated by default)\n  - Delay a job's execution if the previous run hasn't completed yet\n  - Skip a job's execution if the previous run hasn't completed yet\n  - Log each job's invocations\n\nInstall wrappers for all jobs added to a cron using the `cron.WithChain` option:\n\n\tcron.New(cron.WithChain(\n\t\tcron.SkipIfStillRunning(logger),\n\t))\n\nInstall wrappers for individual jobs by explicitly wrapping them:\n\n\tjob = cron.NewChain(\n\t\tcron.SkipIfStillRunning(logger),\n\t).Then(job)\n\nThread safety\n\nSince the Cron service runs concurrently with the calling code, some amount of\ncare must be taken to ensure proper synchronization.\n\nAll cron methods are designed to be correctly synchronized as long as the caller\nensures that invocations have a clear happens-before ordering between them.\n\nLogging\n\nCron defines a Logger interface that is a subset of the one defined in\ngithub.com/go-logr/logr. It has two logging levels (Info and Error), and\nparameters are key/value pairs. This makes it possible for cron logging to plug\ninto structured logging systems. An adapter, [Verbose]PrintfLogger, is provided\nto wrap the standard library *log.Logger.\n\nFor additional insight into Cron operations, verbose logging may be activated\nwhich will record job runs, scheduling decisions, and added or removed jobs.\nActivate it with a one-off logger as follows:\n\n\tcron.New(\n\t\tcron.WithLogger(\n\t\t\tcron.VerbosePrintfLogger(log.New(os.Stdout, \"cron: \", log.LstdFlags))))\n\n\nImplementation\n\nCron entries are stored in an array, sorted by their next activation time.  Cron\nsleeps until the next job is due to be run.\n\nUpon waking:\n - it runs each entry that is active on that second\n - it calculates the next run times for the jobs that were run\n - it re-sorts the array of entries by next activation time.\n - it goes to sleep until the soonest job.\n*/\npackage cron\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/robfig/cron/v3\n\ngo 1.12\n"
  },
  {
    "path": "logger.go",
    "content": "package cron\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\n// DefaultLogger is used by Cron if none is specified.\nvar DefaultLogger Logger = PrintfLogger(log.New(os.Stdout, \"cron: \", log.LstdFlags))\n\n// DiscardLogger can be used by callers to discard all log messages.\nvar DiscardLogger Logger = PrintfLogger(log.New(ioutil.Discard, \"\", 0))\n\n// Logger is the interface used in this package for logging, so that any backend\n// can be plugged in. It is a subset of the github.com/go-logr/logr interface.\ntype Logger interface {\n\t// Info logs routine messages about cron's operation.\n\tInfo(msg string, keysAndValues ...interface{})\n\t// Error logs an error condition.\n\tError(err error, msg string, keysAndValues ...interface{})\n}\n\n// PrintfLogger wraps a Printf-based logger (such as the standard library \"log\")\n// into an implementation of the Logger interface which logs errors only.\nfunc PrintfLogger(l interface{ Printf(string, ...interface{}) }) Logger {\n\treturn printfLogger{l, false}\n}\n\n// VerbosePrintfLogger wraps a Printf-based logger (such as the standard library\n// \"log\") into an implementation of the Logger interface which logs everything.\nfunc VerbosePrintfLogger(l interface{ Printf(string, ...interface{}) }) Logger {\n\treturn printfLogger{l, true}\n}\n\ntype printfLogger struct {\n\tlogger  interface{ Printf(string, ...interface{}) }\n\tlogInfo bool\n}\n\nfunc (pl printfLogger) Info(msg string, keysAndValues ...interface{}) {\n\tif pl.logInfo {\n\t\tkeysAndValues = formatTimes(keysAndValues)\n\t\tpl.logger.Printf(\n\t\t\tformatString(len(keysAndValues)),\n\t\t\tappend([]interface{}{msg}, keysAndValues...)...)\n\t}\n}\n\nfunc (pl printfLogger) Error(err error, msg string, keysAndValues ...interface{}) {\n\tkeysAndValues = formatTimes(keysAndValues)\n\tpl.logger.Printf(\n\t\tformatString(len(keysAndValues)+2),\n\t\tappend([]interface{}{msg, \"error\", err}, keysAndValues...)...)\n}\n\n// formatString returns a logfmt-like format string for the number of\n// key/values.\nfunc formatString(numKeysAndValues int) string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"%s\")\n\tif numKeysAndValues > 0 {\n\t\tsb.WriteString(\", \")\n\t}\n\tfor i := 0; i < numKeysAndValues/2; i++ {\n\t\tif i > 0 {\n\t\t\tsb.WriteString(\", \")\n\t\t}\n\t\tsb.WriteString(\"%v=%v\")\n\t}\n\treturn sb.String()\n}\n\n// formatTimes formats any time.Time values as RFC3339.\nfunc formatTimes(keysAndValues []interface{}) []interface{} {\n\tvar formattedArgs []interface{}\n\tfor _, arg := range keysAndValues {\n\t\tif t, ok := arg.(time.Time); ok {\n\t\t\targ = t.Format(time.RFC3339)\n\t\t}\n\t\tformattedArgs = append(formattedArgs, arg)\n\t}\n\treturn formattedArgs\n}\n"
  },
  {
    "path": "option.go",
    "content": "package cron\n\nimport (\n\t\"time\"\n)\n\n// Option represents a modification to the default behavior of a Cron.\ntype Option func(*Cron)\n\n// WithLocation overrides the timezone of the cron instance.\nfunc WithLocation(loc *time.Location) Option {\n\treturn func(c *Cron) {\n\t\tc.location = loc\n\t}\n}\n\n// WithSeconds overrides the parser used for interpreting job schedules to\n// include a seconds field as the first one.\nfunc WithSeconds() Option {\n\treturn WithParser(NewParser(\n\t\tSecond | Minute | Hour | Dom | Month | Dow | Descriptor,\n\t))\n}\n\n// WithParser overrides the parser used for interpreting job schedules.\nfunc WithParser(p ScheduleParser) Option {\n\treturn func(c *Cron) {\n\t\tc.parser = p\n\t}\n}\n\n// WithChain specifies Job wrappers to apply to all jobs added to this cron.\n// Refer to the Chain* functions in this package for provided wrappers.\nfunc WithChain(wrappers ...JobWrapper) Option {\n\treturn func(c *Cron) {\n\t\tc.chain = NewChain(wrappers...)\n\t}\n}\n\n// WithLogger uses the provided logger.\nfunc WithLogger(logger Logger) Option {\n\treturn func(c *Cron) {\n\t\tc.logger = logger\n\t}\n}\n"
  },
  {
    "path": "option_test.go",
    "content": "package cron\n\nimport (\n\t\"log\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestWithLocation(t *testing.T) {\n\tc := New(WithLocation(time.UTC))\n\tif c.location != time.UTC {\n\t\tt.Errorf(\"expected UTC, got %v\", c.location)\n\t}\n}\n\nfunc TestWithParser(t *testing.T) {\n\tvar parser = NewParser(Dow)\n\tc := New(WithParser(parser))\n\tif c.parser != parser {\n\t\tt.Error(\"expected provided parser\")\n\t}\n}\n\nfunc TestWithVerboseLogger(t *testing.T) {\n\tvar buf syncWriter\n\tvar logger = log.New(&buf, \"\", log.LstdFlags)\n\tc := New(WithLogger(VerbosePrintfLogger(logger)))\n\tif c.logger.(printfLogger).logger != logger {\n\t\tt.Error(\"expected provided logger\")\n\t}\n\n\tc.AddFunc(\"@every 1s\", func() {})\n\tc.Start()\n\ttime.Sleep(OneSecond)\n\tc.Stop()\n\tout := buf.String()\n\tif !strings.Contains(out, \"schedule,\") ||\n\t\t!strings.Contains(out, \"run,\") {\n\t\tt.Error(\"expected to see some actions, got:\", out)\n\t}\n}\n"
  },
  {
    "path": "parser.go",
    "content": "package cron\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// Configuration options for creating a parser. Most options specify which\n// fields should be included, while others enable features. If a field is not\n// included the parser will assume a default value. These options do not change\n// the order fields are parse in.\ntype ParseOption int\n\nconst (\n\tSecond         ParseOption = 1 << iota // Seconds field, default 0\n\tSecondOptional                         // Optional seconds field, default 0\n\tMinute                                 // Minutes field, default 0\n\tHour                                   // Hours field, default 0\n\tDom                                    // Day of month field, default *\n\tMonth                                  // Month field, default *\n\tDow                                    // Day of week field, default *\n\tDowOptional                            // Optional day of week field, default *\n\tDescriptor                             // Allow descriptors such as @monthly, @weekly, etc.\n)\n\nvar places = []ParseOption{\n\tSecond,\n\tMinute,\n\tHour,\n\tDom,\n\tMonth,\n\tDow,\n}\n\nvar defaults = []string{\n\t\"0\",\n\t\"0\",\n\t\"0\",\n\t\"*\",\n\t\"*\",\n\t\"*\",\n}\n\n// A custom Parser that can be configured.\ntype Parser struct {\n\toptions ParseOption\n}\n\n// NewParser creates a Parser with custom options.\n//\n// It panics if more than one Optional is given, since it would be impossible to\n// correctly infer which optional is provided or missing in general.\n//\n// Examples\n//\n//  // Standard parser without descriptors\n//  specParser := NewParser(Minute | Hour | Dom | Month | Dow)\n//  sched, err := specParser.Parse(\"0 0 15 */3 *\")\n//\n//  // Same as above, just excludes time fields\n//  specParser := NewParser(Dom | Month | Dow)\n//  sched, err := specParser.Parse(\"15 */3 *\")\n//\n//  // Same as above, just makes Dow optional\n//  specParser := NewParser(Dom | Month | DowOptional)\n//  sched, err := specParser.Parse(\"15 */3\")\n//\nfunc NewParser(options ParseOption) Parser {\n\toptionals := 0\n\tif options&DowOptional > 0 {\n\t\toptionals++\n\t}\n\tif options&SecondOptional > 0 {\n\t\toptionals++\n\t}\n\tif optionals > 1 {\n\t\tpanic(\"multiple optionals may not be configured\")\n\t}\n\treturn Parser{options}\n}\n\n// Parse returns a new crontab schedule representing the given spec.\n// It returns a descriptive error if the spec is not valid.\n// It accepts crontab specs and features configured by NewParser.\nfunc (p Parser) Parse(spec string) (Schedule, error) {\n\tif len(spec) == 0 {\n\t\treturn nil, fmt.Errorf(\"empty spec string\")\n\t}\n\n\t// Extract timezone if present\n\tvar loc = time.Local\n\tif strings.HasPrefix(spec, \"TZ=\") || strings.HasPrefix(spec, \"CRON_TZ=\") {\n\t\tvar err error\n\t\ti := strings.Index(spec, \" \")\n\t\teq := strings.Index(spec, \"=\")\n\t\tif loc, err = time.LoadLocation(spec[eq+1 : i]); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"provided bad location %s: %v\", spec[eq+1:i], err)\n\t\t}\n\t\tspec = strings.TrimSpace(spec[i:])\n\t}\n\n\t// Handle named schedules (descriptors), if configured\n\tif strings.HasPrefix(spec, \"@\") {\n\t\tif p.options&Descriptor == 0 {\n\t\t\treturn nil, fmt.Errorf(\"parser does not accept descriptors: %v\", spec)\n\t\t}\n\t\treturn parseDescriptor(spec, loc)\n\t}\n\n\t// Split on whitespace.\n\tfields := strings.Fields(spec)\n\n\t// Validate & fill in any omitted or optional fields\n\tvar err error\n\tfields, err = normalizeFields(fields, p.options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfield := func(field string, r bounds) uint64 {\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\tvar bits uint64\n\t\tbits, err = getField(field, r)\n\t\treturn bits\n\t}\n\n\tvar (\n\t\tsecond     = field(fields[0], seconds)\n\t\tminute     = field(fields[1], minutes)\n\t\thour       = field(fields[2], hours)\n\t\tdayofmonth = field(fields[3], dom)\n\t\tmonth      = field(fields[4], months)\n\t\tdayofweek  = field(fields[5], dow)\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &SpecSchedule{\n\t\tSecond:   second,\n\t\tMinute:   minute,\n\t\tHour:     hour,\n\t\tDom:      dayofmonth,\n\t\tMonth:    month,\n\t\tDow:      dayofweek,\n\t\tLocation: loc,\n\t}, nil\n}\n\n// normalizeFields takes a subset set of the time fields and returns the full set\n// with defaults (zeroes) populated for unset fields.\n//\n// As part of performing this function, it also validates that the provided\n// fields are compatible with the configured options.\nfunc normalizeFields(fields []string, options ParseOption) ([]string, error) {\n\t// Validate optionals & add their field to options\n\toptionals := 0\n\tif options&SecondOptional > 0 {\n\t\toptions |= Second\n\t\toptionals++\n\t}\n\tif options&DowOptional > 0 {\n\t\toptions |= Dow\n\t\toptionals++\n\t}\n\tif optionals > 1 {\n\t\treturn nil, fmt.Errorf(\"multiple optionals may not be configured\")\n\t}\n\n\t// Figure out how many fields we need\n\tmax := 0\n\tfor _, place := range places {\n\t\tif options&place > 0 {\n\t\t\tmax++\n\t\t}\n\t}\n\tmin := max - optionals\n\n\t// Validate number of fields\n\tif count := len(fields); count < min || count > max {\n\t\tif min == max {\n\t\t\treturn nil, fmt.Errorf(\"expected exactly %d fields, found %d: %s\", min, count, fields)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"expected %d to %d fields, found %d: %s\", min, max, count, fields)\n\t}\n\n\t// Populate the optional field if not provided\n\tif min < max && len(fields) == min {\n\t\tswitch {\n\t\tcase options&DowOptional > 0:\n\t\t\tfields = append(fields, defaults[5]) // TODO: improve access to default\n\t\tcase options&SecondOptional > 0:\n\t\t\tfields = append([]string{defaults[0]}, fields...)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown optional field\")\n\t\t}\n\t}\n\n\t// Populate all fields not part of options with their defaults\n\tn := 0\n\texpandedFields := make([]string, len(places))\n\tcopy(expandedFields, defaults)\n\tfor i, place := range places {\n\t\tif options&place > 0 {\n\t\t\texpandedFields[i] = fields[n]\n\t\t\tn++\n\t\t}\n\t}\n\treturn expandedFields, nil\n}\n\nvar standardParser = NewParser(\n\tMinute | Hour | Dom | Month | Dow | Descriptor,\n)\n\n// ParseStandard returns a new crontab schedule representing the given\n// standardSpec (https://en.wikipedia.org/wiki/Cron). It requires 5 entries\n// representing: minute, hour, day of month, month and day of week, in that\n// order. It returns a descriptive error if the spec is not valid.\n//\n// It accepts\n//   - Standard crontab specs, e.g. \"* * * * ?\"\n//   - Descriptors, e.g. \"@midnight\", \"@every 1h30m\"\nfunc ParseStandard(standardSpec string) (Schedule, error) {\n\treturn standardParser.Parse(standardSpec)\n}\n\n// getField returns an Int with the bits set representing all of the times that\n// the field represents or error parsing field value.  A \"field\" is a comma-separated\n// list of \"ranges\".\nfunc getField(field string, r bounds) (uint64, error) {\n\tvar bits uint64\n\tranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' })\n\tfor _, expr := range ranges {\n\t\tbit, err := getRange(expr, r)\n\t\tif err != nil {\n\t\t\treturn bits, err\n\t\t}\n\t\tbits |= bit\n\t}\n\treturn bits, nil\n}\n\n// getRange returns the bits indicated by the given expression:\n//   number | number \"-\" number [ \"/\" number ]\n// or error parsing range.\nfunc getRange(expr string, r bounds) (uint64, error) {\n\tvar (\n\t\tstart, end, step uint\n\t\trangeAndStep     = strings.Split(expr, \"/\")\n\t\tlowAndHigh       = strings.Split(rangeAndStep[0], \"-\")\n\t\tsingleDigit      = len(lowAndHigh) == 1\n\t\terr              error\n\t)\n\n\tvar extra uint64\n\tif lowAndHigh[0] == \"*\" || lowAndHigh[0] == \"?\" {\n\t\tstart = r.min\n\t\tend = r.max\n\t\textra = starBit\n\t} else {\n\t\tstart, err = parseIntOrName(lowAndHigh[0], r.names)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tswitch len(lowAndHigh) {\n\t\tcase 1:\n\t\t\tend = start\n\t\tcase 2:\n\t\t\tend, err = parseIntOrName(lowAndHigh[1], r.names)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn 0, fmt.Errorf(\"too many hyphens: %s\", expr)\n\t\t}\n\t}\n\n\tswitch len(rangeAndStep) {\n\tcase 1:\n\t\tstep = 1\n\tcase 2:\n\t\tstep, err = mustParseInt(rangeAndStep[1])\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\t// Special handling: \"N/step\" means \"N-max/step\".\n\t\tif singleDigit {\n\t\t\tend = r.max\n\t\t}\n\t\tif step > 1 {\n\t\t\textra = 0\n\t\t}\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"too many slashes: %s\", expr)\n\t}\n\n\tif start < r.min {\n\t\treturn 0, fmt.Errorf(\"beginning of range (%d) below minimum (%d): %s\", start, r.min, expr)\n\t}\n\tif end > r.max {\n\t\treturn 0, fmt.Errorf(\"end of range (%d) above maximum (%d): %s\", end, r.max, expr)\n\t}\n\tif start > end {\n\t\treturn 0, fmt.Errorf(\"beginning of range (%d) beyond end of range (%d): %s\", start, end, expr)\n\t}\n\tif step == 0 {\n\t\treturn 0, fmt.Errorf(\"step of range should be a positive number: %s\", expr)\n\t}\n\n\treturn getBits(start, end, step) | extra, nil\n}\n\n// parseIntOrName returns the (possibly-named) integer contained in expr.\nfunc parseIntOrName(expr string, names map[string]uint) (uint, error) {\n\tif names != nil {\n\t\tif namedInt, ok := names[strings.ToLower(expr)]; ok {\n\t\t\treturn namedInt, nil\n\t\t}\n\t}\n\treturn mustParseInt(expr)\n}\n\n// mustParseInt parses the given expression as an int or returns an error.\nfunc mustParseInt(expr string) (uint, error) {\n\tnum, err := strconv.Atoi(expr)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to parse int from %s: %s\", expr, err)\n\t}\n\tif num < 0 {\n\t\treturn 0, fmt.Errorf(\"negative number (%d) not allowed: %s\", num, expr)\n\t}\n\n\treturn uint(num), nil\n}\n\n// getBits sets all bits in the range [min, max], modulo the given step size.\nfunc getBits(min, max, step uint) uint64 {\n\tvar bits uint64\n\n\t// If step is 1, use shifts.\n\tif step == 1 {\n\t\treturn ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min)\n\t}\n\n\t// Else, use a simple loop.\n\tfor i := min; i <= max; i += step {\n\t\tbits |= 1 << i\n\t}\n\treturn bits\n}\n\n// all returns all bits within the given bounds.  (plus the star bit)\nfunc all(r bounds) uint64 {\n\treturn getBits(r.min, r.max, 1) | starBit\n}\n\n// parseDescriptor returns a predefined schedule for the expression, or error if none matches.\nfunc parseDescriptor(descriptor string, loc *time.Location) (Schedule, error) {\n\tswitch descriptor {\n\tcase \"@yearly\", \"@annually\":\n\t\treturn &SpecSchedule{\n\t\t\tSecond:   1 << seconds.min,\n\t\t\tMinute:   1 << minutes.min,\n\t\t\tHour:     1 << hours.min,\n\t\t\tDom:      1 << dom.min,\n\t\t\tMonth:    1 << months.min,\n\t\t\tDow:      all(dow),\n\t\t\tLocation: loc,\n\t\t}, nil\n\n\tcase \"@monthly\":\n\t\treturn &SpecSchedule{\n\t\t\tSecond:   1 << seconds.min,\n\t\t\tMinute:   1 << minutes.min,\n\t\t\tHour:     1 << hours.min,\n\t\t\tDom:      1 << dom.min,\n\t\t\tMonth:    all(months),\n\t\t\tDow:      all(dow),\n\t\t\tLocation: loc,\n\t\t}, nil\n\n\tcase \"@weekly\":\n\t\treturn &SpecSchedule{\n\t\t\tSecond:   1 << seconds.min,\n\t\t\tMinute:   1 << minutes.min,\n\t\t\tHour:     1 << hours.min,\n\t\t\tDom:      all(dom),\n\t\t\tMonth:    all(months),\n\t\t\tDow:      1 << dow.min,\n\t\t\tLocation: loc,\n\t\t}, nil\n\n\tcase \"@daily\", \"@midnight\":\n\t\treturn &SpecSchedule{\n\t\t\tSecond:   1 << seconds.min,\n\t\t\tMinute:   1 << minutes.min,\n\t\t\tHour:     1 << hours.min,\n\t\t\tDom:      all(dom),\n\t\t\tMonth:    all(months),\n\t\t\tDow:      all(dow),\n\t\t\tLocation: loc,\n\t\t}, nil\n\n\tcase \"@hourly\":\n\t\treturn &SpecSchedule{\n\t\t\tSecond:   1 << seconds.min,\n\t\t\tMinute:   1 << minutes.min,\n\t\t\tHour:     all(hours),\n\t\t\tDom:      all(dom),\n\t\t\tMonth:    all(months),\n\t\t\tDow:      all(dow),\n\t\t\tLocation: loc,\n\t\t}, nil\n\n\t}\n\n\tconst every = \"@every \"\n\tif strings.HasPrefix(descriptor, every) {\n\t\tduration, err := time.ParseDuration(descriptor[len(every):])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse duration %s: %s\", descriptor, err)\n\t\t}\n\t\treturn Every(duration), nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unrecognized descriptor: %s\", descriptor)\n}\n"
  },
  {
    "path": "parser_test.go",
    "content": "package cron\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar secondParser = NewParser(Second | Minute | Hour | Dom | Month | DowOptional | Descriptor)\n\nfunc TestRange(t *testing.T) {\n\tzero := uint64(0)\n\tranges := []struct {\n\t\texpr     string\n\t\tmin, max uint\n\t\texpected uint64\n\t\terr      string\n\t}{\n\t\t{\"5\", 0, 7, 1 << 5, \"\"},\n\t\t{\"0\", 0, 7, 1 << 0, \"\"},\n\t\t{\"7\", 0, 7, 1 << 7, \"\"},\n\n\t\t{\"5-5\", 0, 7, 1 << 5, \"\"},\n\t\t{\"5-6\", 0, 7, 1<<5 | 1<<6, \"\"},\n\t\t{\"5-7\", 0, 7, 1<<5 | 1<<6 | 1<<7, \"\"},\n\n\t\t{\"5-6/2\", 0, 7, 1 << 5, \"\"},\n\t\t{\"5-7/2\", 0, 7, 1<<5 | 1<<7, \"\"},\n\t\t{\"5-7/1\", 0, 7, 1<<5 | 1<<6 | 1<<7, \"\"},\n\n\t\t{\"*\", 1, 3, 1<<1 | 1<<2 | 1<<3 | starBit, \"\"},\n\t\t{\"*/2\", 1, 3, 1<<1 | 1<<3, \"\"},\n\n\t\t{\"5--5\", 0, 0, zero, \"too many hyphens\"},\n\t\t{\"jan-x\", 0, 0, zero, \"failed to parse int from\"},\n\t\t{\"2-x\", 1, 5, zero, \"failed to parse int from\"},\n\t\t{\"*/-12\", 0, 0, zero, \"negative number\"},\n\t\t{\"*//2\", 0, 0, zero, \"too many slashes\"},\n\t\t{\"1\", 3, 5, zero, \"below minimum\"},\n\t\t{\"6\", 3, 5, zero, \"above maximum\"},\n\t\t{\"5-3\", 3, 5, zero, \"beyond end of range\"},\n\t\t{\"*/0\", 0, 0, zero, \"should be a positive number\"},\n\t}\n\n\tfor _, c := range ranges {\n\t\tactual, err := getRange(c.expr, bounds{c.min, c.max, nil})\n\t\tif len(c.err) != 0 && (err == nil || !strings.Contains(err.Error(), c.err)) {\n\t\t\tt.Errorf(\"%s => expected %v, got %v\", c.expr, c.err, err)\n\t\t}\n\t\tif len(c.err) == 0 && err != nil {\n\t\t\tt.Errorf(\"%s => unexpected error %v\", c.expr, err)\n\t\t}\n\t\tif actual != c.expected {\n\t\t\tt.Errorf(\"%s => expected %d, got %d\", c.expr, c.expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestField(t *testing.T) {\n\tfields := []struct {\n\t\texpr     string\n\t\tmin, max uint\n\t\texpected uint64\n\t}{\n\t\t{\"5\", 1, 7, 1 << 5},\n\t\t{\"5,6\", 1, 7, 1<<5 | 1<<6},\n\t\t{\"5,6,7\", 1, 7, 1<<5 | 1<<6 | 1<<7},\n\t\t{\"1,5-7/2,3\", 1, 7, 1<<1 | 1<<5 | 1<<7 | 1<<3},\n\t}\n\n\tfor _, c := range fields {\n\t\tactual, _ := getField(c.expr, bounds{c.min, c.max, nil})\n\t\tif actual != c.expected {\n\t\t\tt.Errorf(\"%s => expected %d, got %d\", c.expr, c.expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestAll(t *testing.T) {\n\tallBits := []struct {\n\t\tr        bounds\n\t\texpected uint64\n\t}{\n\t\t{minutes, 0xfffffffffffffff}, // 0-59: 60 ones\n\t\t{hours, 0xffffff},            // 0-23: 24 ones\n\t\t{dom, 0xfffffffe},            // 1-31: 31 ones, 1 zero\n\t\t{months, 0x1ffe},             // 1-12: 12 ones, 1 zero\n\t\t{dow, 0x7f},                  // 0-6: 7 ones\n\t}\n\n\tfor _, c := range allBits {\n\t\tactual := all(c.r) // all() adds the starBit, so compensate for that..\n\t\tif c.expected|starBit != actual {\n\t\t\tt.Errorf(\"%d-%d/%d => expected %b, got %b\",\n\t\t\t\tc.r.min, c.r.max, 1, c.expected|starBit, actual)\n\t\t}\n\t}\n}\n\nfunc TestBits(t *testing.T) {\n\tbits := []struct {\n\t\tmin, max, step uint\n\t\texpected       uint64\n\t}{\n\t\t{0, 0, 1, 0x1},\n\t\t{1, 1, 1, 0x2},\n\t\t{1, 5, 2, 0x2a}, // 101010\n\t\t{1, 4, 2, 0xa},  // 1010\n\t}\n\n\tfor _, c := range bits {\n\t\tactual := getBits(c.min, c.max, c.step)\n\t\tif c.expected != actual {\n\t\t\tt.Errorf(\"%d-%d/%d => expected %b, got %b\",\n\t\t\t\tc.min, c.max, c.step, c.expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestParseScheduleErrors(t *testing.T) {\n\tvar tests = []struct{ expr, err string }{\n\t\t{\"* 5 j * * *\", \"failed to parse int from\"},\n\t\t{\"@every Xm\", \"failed to parse duration\"},\n\t\t{\"@unrecognized\", \"unrecognized descriptor\"},\n\t\t{\"* * * *\", \"expected 5 to 6 fields\"},\n\t\t{\"\", \"empty spec string\"},\n\t}\n\tfor _, c := range tests {\n\t\tactual, err := secondParser.Parse(c.expr)\n\t\tif err == nil || !strings.Contains(err.Error(), c.err) {\n\t\t\tt.Errorf(\"%s => expected %v, got %v\", c.expr, c.err, err)\n\t\t}\n\t\tif actual != nil {\n\t\t\tt.Errorf(\"expected nil schedule on error, got %v\", actual)\n\t\t}\n\t}\n}\n\nfunc TestParseSchedule(t *testing.T) {\n\ttokyo, _ := time.LoadLocation(\"Asia/Tokyo\")\n\tentries := []struct {\n\t\tparser   Parser\n\t\texpr     string\n\t\texpected Schedule\n\t}{\n\t\t{secondParser, \"0 5 * * * *\", every5min(time.Local)},\n\t\t{standardParser, \"5 * * * *\", every5min(time.Local)},\n\t\t{secondParser, \"CRON_TZ=UTC  0 5 * * * *\", every5min(time.UTC)},\n\t\t{standardParser, \"CRON_TZ=UTC  5 * * * *\", every5min(time.UTC)},\n\t\t{secondParser, \"CRON_TZ=Asia/Tokyo 0 5 * * * *\", every5min(tokyo)},\n\t\t{secondParser, \"@every 5m\", ConstantDelaySchedule{5 * time.Minute}},\n\t\t{secondParser, \"@midnight\", midnight(time.Local)},\n\t\t{secondParser, \"TZ=UTC  @midnight\", midnight(time.UTC)},\n\t\t{secondParser, \"TZ=Asia/Tokyo @midnight\", midnight(tokyo)},\n\t\t{secondParser, \"@yearly\", annual(time.Local)},\n\t\t{secondParser, \"@annually\", annual(time.Local)},\n\t\t{\n\t\t\tparser: secondParser,\n\t\t\texpr:   \"* 5 * * * *\",\n\t\t\texpected: &SpecSchedule{\n\t\t\t\tSecond:   all(seconds),\n\t\t\t\tMinute:   1 << 5,\n\t\t\t\tHour:     all(hours),\n\t\t\t\tDom:      all(dom),\n\t\t\t\tMonth:    all(months),\n\t\t\t\tDow:      all(dow),\n\t\t\t\tLocation: time.Local,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, c := range entries {\n\t\tactual, err := c.parser.Parse(c.expr)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s => unexpected error %v\", c.expr, err)\n\t\t}\n\t\tif !reflect.DeepEqual(actual, c.expected) {\n\t\t\tt.Errorf(\"%s => expected %b, got %b\", c.expr, c.expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestOptionalSecondSchedule(t *testing.T) {\n\tparser := NewParser(SecondOptional | Minute | Hour | Dom | Month | Dow | Descriptor)\n\tentries := []struct {\n\t\texpr     string\n\t\texpected Schedule\n\t}{\n\t\t{\"0 5 * * * *\", every5min(time.Local)},\n\t\t{\"5 5 * * * *\", every5min5s(time.Local)},\n\t\t{\"5 * * * *\", every5min(time.Local)},\n\t}\n\n\tfor _, c := range entries {\n\t\tactual, err := parser.Parse(c.expr)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s => unexpected error %v\", c.expr, err)\n\t\t}\n\t\tif !reflect.DeepEqual(actual, c.expected) {\n\t\t\tt.Errorf(\"%s => expected %b, got %b\", c.expr, c.expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestNormalizeFields(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []string\n\t\toptions  ParseOption\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\t\"AllFields_NoOptional\",\n\t\t\t[]string{\"0\", \"5\", \"*\", \"*\", \"*\", \"*\"},\n\t\t\tSecond | Minute | Hour | Dom | Month | Dow | Descriptor,\n\t\t\t[]string{\"0\", \"5\", \"*\", \"*\", \"*\", \"*\"},\n\t\t},\n\t\t{\n\t\t\t\"AllFields_SecondOptional_Provided\",\n\t\t\t[]string{\"0\", \"5\", \"*\", \"*\", \"*\", \"*\"},\n\t\t\tSecondOptional | Minute | Hour | Dom | Month | Dow | Descriptor,\n\t\t\t[]string{\"0\", \"5\", \"*\", \"*\", \"*\", \"*\"},\n\t\t},\n\t\t{\n\t\t\t\"AllFields_SecondOptional_NotProvided\",\n\t\t\t[]string{\"5\", \"*\", \"*\", \"*\", \"*\"},\n\t\t\tSecondOptional | Minute | Hour | Dom | Month | Dow | Descriptor,\n\t\t\t[]string{\"0\", \"5\", \"*\", \"*\", \"*\", \"*\"},\n\t\t},\n\t\t{\n\t\t\t\"SubsetFields_NoOptional\",\n\t\t\t[]string{\"5\", \"15\", \"*\"},\n\t\t\tHour | Dom | Month,\n\t\t\t[]string{\"0\", \"0\", \"5\", \"15\", \"*\", \"*\"},\n\t\t},\n\t\t{\n\t\t\t\"SubsetFields_DowOptional_Provided\",\n\t\t\t[]string{\"5\", \"15\", \"*\", \"4\"},\n\t\t\tHour | Dom | Month | DowOptional,\n\t\t\t[]string{\"0\", \"0\", \"5\", \"15\", \"*\", \"4\"},\n\t\t},\n\t\t{\n\t\t\t\"SubsetFields_DowOptional_NotProvided\",\n\t\t\t[]string{\"5\", \"15\", \"*\"},\n\t\t\tHour | Dom | Month | DowOptional,\n\t\t\t[]string{\"0\", \"0\", \"5\", \"15\", \"*\", \"*\"},\n\t\t},\n\t\t{\n\t\t\t\"SubsetFields_SecondOptional_NotProvided\",\n\t\t\t[]string{\"5\", \"15\", \"*\"},\n\t\t\tSecondOptional | Hour | Dom | Month,\n\t\t\t[]string{\"0\", \"0\", \"5\", \"15\", \"*\", \"*\"},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactual, err := normalizeFields(test.input, test.options)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"unexpected error: %v\", err)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(actual, test.expected) {\n\t\t\t\tt.Errorf(\"expected %v, got %v\", test.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNormalizeFields_Errors(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tinput   []string\n\t\toptions ParseOption\n\t\terr     string\n\t}{\n\t\t{\n\t\t\t\"TwoOptionals\",\n\t\t\t[]string{\"0\", \"5\", \"*\", \"*\", \"*\", \"*\"},\n\t\t\tSecondOptional | Minute | Hour | Dom | Month | DowOptional,\n\t\t\t\"\",\n\t\t},\n\t\t{\n\t\t\t\"TooManyFields\",\n\t\t\t[]string{\"0\", \"5\", \"*\", \"*\"},\n\t\t\tSecondOptional | Minute | Hour,\n\t\t\t\"\",\n\t\t},\n\t\t{\n\t\t\t\"NoFields\",\n\t\t\t[]string{},\n\t\t\tSecondOptional | Minute | Hour,\n\t\t\t\"\",\n\t\t},\n\t\t{\n\t\t\t\"TooFewFields\",\n\t\t\t[]string{\"*\"},\n\t\t\tSecondOptional | Minute | Hour,\n\t\t\t\"\",\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactual, err := normalizeFields(test.input, test.options)\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"expected an error, got none. results: %v\", actual)\n\t\t\t}\n\t\t\tif !strings.Contains(err.Error(), test.err) {\n\t\t\t\tt.Errorf(\"expected error %q, got %q\", test.err, err.Error())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestStandardSpecSchedule(t *testing.T) {\n\tentries := []struct {\n\t\texpr     string\n\t\texpected Schedule\n\t\terr      string\n\t}{\n\t\t{\n\t\t\texpr:     \"5 * * * *\",\n\t\t\texpected: &SpecSchedule{1 << seconds.min, 1 << 5, all(hours), all(dom), all(months), all(dow), time.Local},\n\t\t},\n\t\t{\n\t\t\texpr:     \"@every 5m\",\n\t\t\texpected: ConstantDelaySchedule{time.Duration(5) * time.Minute},\n\t\t},\n\t\t{\n\t\t\texpr: \"5 j * * *\",\n\t\t\terr:  \"failed to parse int from\",\n\t\t},\n\t\t{\n\t\t\texpr: \"* * * *\",\n\t\t\terr:  \"expected exactly 5 fields\",\n\t\t},\n\t}\n\n\tfor _, c := range entries {\n\t\tactual, err := ParseStandard(c.expr)\n\t\tif len(c.err) != 0 && (err == nil || !strings.Contains(err.Error(), c.err)) {\n\t\t\tt.Errorf(\"%s => expected %v, got %v\", c.expr, c.err, err)\n\t\t}\n\t\tif len(c.err) == 0 && err != nil {\n\t\t\tt.Errorf(\"%s => unexpected error %v\", c.expr, err)\n\t\t}\n\t\tif !reflect.DeepEqual(actual, c.expected) {\n\t\t\tt.Errorf(\"%s => expected %b, got %b\", c.expr, c.expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestNoDescriptorParser(t *testing.T) {\n\tparser := NewParser(Minute | Hour)\n\t_, err := parser.Parse(\"@every 1m\")\n\tif err == nil {\n\t\tt.Error(\"expected an error, got none\")\n\t}\n}\n\nfunc every5min(loc *time.Location) *SpecSchedule {\n\treturn &SpecSchedule{1 << 0, 1 << 5, all(hours), all(dom), all(months), all(dow), loc}\n}\n\nfunc every5min5s(loc *time.Location) *SpecSchedule {\n\treturn &SpecSchedule{1 << 5, 1 << 5, all(hours), all(dom), all(months), all(dow), loc}\n}\n\nfunc midnight(loc *time.Location) *SpecSchedule {\n\treturn &SpecSchedule{1, 1, 1, all(dom), all(months), all(dow), loc}\n}\n\nfunc annual(loc *time.Location) *SpecSchedule {\n\treturn &SpecSchedule{\n\t\tSecond:   1 << seconds.min,\n\t\tMinute:   1 << minutes.min,\n\t\tHour:     1 << hours.min,\n\t\tDom:      1 << dom.min,\n\t\tMonth:    1 << months.min,\n\t\tDow:      all(dow),\n\t\tLocation: loc,\n\t}\n}\n"
  },
  {
    "path": "spec.go",
    "content": "package cron\n\nimport \"time\"\n\n// SpecSchedule specifies a duty cycle (to the second granularity), based on a\n// traditional crontab specification. It is computed initially and stored as bit sets.\ntype SpecSchedule struct {\n\tSecond, Minute, Hour, Dom, Month, Dow uint64\n\n\t// Override location for this schedule.\n\tLocation *time.Location\n}\n\n// bounds provides a range of acceptable values (plus a map of name to value).\ntype bounds struct {\n\tmin, max uint\n\tnames    map[string]uint\n}\n\n// The bounds for each field.\nvar (\n\tseconds = bounds{0, 59, nil}\n\tminutes = bounds{0, 59, nil}\n\thours   = bounds{0, 23, nil}\n\tdom     = bounds{1, 31, nil}\n\tmonths  = bounds{1, 12, map[string]uint{\n\t\t\"jan\": 1,\n\t\t\"feb\": 2,\n\t\t\"mar\": 3,\n\t\t\"apr\": 4,\n\t\t\"may\": 5,\n\t\t\"jun\": 6,\n\t\t\"jul\": 7,\n\t\t\"aug\": 8,\n\t\t\"sep\": 9,\n\t\t\"oct\": 10,\n\t\t\"nov\": 11,\n\t\t\"dec\": 12,\n\t}}\n\tdow = bounds{0, 6, map[string]uint{\n\t\t\"sun\": 0,\n\t\t\"mon\": 1,\n\t\t\"tue\": 2,\n\t\t\"wed\": 3,\n\t\t\"thu\": 4,\n\t\t\"fri\": 5,\n\t\t\"sat\": 6,\n\t}}\n)\n\nconst (\n\t// Set the top bit if a star was included in the expression.\n\tstarBit = 1 << 63\n)\n\n// Next returns the next time this schedule is activated, greater than the given\n// time.  If no time can be found to satisfy the schedule, return the zero time.\nfunc (s *SpecSchedule) Next(t time.Time) time.Time {\n\t// General approach\n\t//\n\t// For Month, Day, Hour, Minute, Second:\n\t// Check if the time value matches.  If yes, continue to the next field.\n\t// If the field doesn't match the schedule, then increment the field until it matches.\n\t// While incrementing the field, a wrap-around brings it back to the beginning\n\t// of the field list (since it is necessary to re-verify previous field\n\t// values)\n\n\t// Convert the given time into the schedule's timezone, if one is specified.\n\t// Save the original timezone so we can convert back after we find a time.\n\t// Note that schedules without a time zone specified (time.Local) are treated\n\t// as local to the time provided.\n\torigLocation := t.Location()\n\tloc := s.Location\n\tif loc == time.Local {\n\t\tloc = t.Location()\n\t}\n\tif s.Location != time.Local {\n\t\tt = t.In(s.Location)\n\t}\n\n\t// Start at the earliest possible time (the upcoming second).\n\tt = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond)\n\n\t// This flag indicates whether a field has been incremented.\n\tadded := false\n\n\t// If no time is found within five years, return zero.\n\tyearLimit := t.Year() + 5\n\nWRAP:\n\tif t.Year() > yearLimit {\n\t\treturn time.Time{}\n\t}\n\n\t// Find the first applicable month.\n\t// If it's this month, then do nothing.\n\tfor 1<<uint(t.Month())&s.Month == 0 {\n\t\t// If we have to add a month, reset the other parts to 0.\n\t\tif !added {\n\t\t\tadded = true\n\t\t\t// Otherwise, set the date at the beginning (since the current time is irrelevant).\n\t\t\tt = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, loc)\n\t\t}\n\t\tt = t.AddDate(0, 1, 0)\n\n\t\t// Wrapped around.\n\t\tif t.Month() == time.January {\n\t\t\tgoto WRAP\n\t\t}\n\t}\n\n\t// Now get a day in that month.\n\t//\n\t// NOTE: This causes issues for daylight savings regimes where midnight does\n\t// not exist.  For example: Sao Paulo has DST that transforms midnight on\n\t// 11/3 into 1am. Handle that by noticing when the Hour ends up != 0.\n\tfor !dayMatches(s, t) {\n\t\tif !added {\n\t\t\tadded = true\n\t\t\tt = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, loc)\n\t\t}\n\t\tt = t.AddDate(0, 0, 1)\n\t\t// Notice if the hour is no longer midnight due to DST.\n\t\t// Add an hour if it's 23, subtract an hour if it's 1.\n\t\tif t.Hour() != 0 {\n\t\t\tif t.Hour() > 12 {\n\t\t\t\tt = t.Add(time.Duration(24-t.Hour()) * time.Hour)\n\t\t\t} else {\n\t\t\t\tt = t.Add(time.Duration(-t.Hour()) * time.Hour)\n\t\t\t}\n\t\t}\n\n\t\tif t.Day() == 1 {\n\t\t\tgoto WRAP\n\t\t}\n\t}\n\n\tfor 1<<uint(t.Hour())&s.Hour == 0 {\n\t\tif !added {\n\t\t\tadded = true\n\t\t\tt = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, loc)\n\t\t}\n\t\tt = t.Add(1 * time.Hour)\n\n\t\tif t.Hour() == 0 {\n\t\t\tgoto WRAP\n\t\t}\n\t}\n\n\tfor 1<<uint(t.Minute())&s.Minute == 0 {\n\t\tif !added {\n\t\t\tadded = true\n\t\t\tt = t.Truncate(time.Minute)\n\t\t}\n\t\tt = t.Add(1 * time.Minute)\n\n\t\tif t.Minute() == 0 {\n\t\t\tgoto WRAP\n\t\t}\n\t}\n\n\tfor 1<<uint(t.Second())&s.Second == 0 {\n\t\tif !added {\n\t\t\tadded = true\n\t\t\tt = t.Truncate(time.Second)\n\t\t}\n\t\tt = t.Add(1 * time.Second)\n\n\t\tif t.Second() == 0 {\n\t\t\tgoto WRAP\n\t\t}\n\t}\n\n\treturn t.In(origLocation)\n}\n\n// dayMatches returns true if the schedule's day-of-week and day-of-month\n// restrictions are satisfied by the given time.\nfunc dayMatches(s *SpecSchedule, t time.Time) bool {\n\tvar (\n\t\tdomMatch bool = 1<<uint(t.Day())&s.Dom > 0\n\t\tdowMatch bool = 1<<uint(t.Weekday())&s.Dow > 0\n\t)\n\tif s.Dom&starBit > 0 || s.Dow&starBit > 0 {\n\t\treturn domMatch && dowMatch\n\t}\n\treturn domMatch || dowMatch\n}\n"
  },
  {
    "path": "spec_test.go",
    "content": "package cron\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestActivation(t *testing.T) {\n\ttests := []struct {\n\t\ttime, spec string\n\t\texpected   bool\n\t}{\n\t\t// Every fifteen minutes.\n\t\t{\"Mon Jul 9 15:00 2012\", \"0/15 * * * *\", true},\n\t\t{\"Mon Jul 9 15:45 2012\", \"0/15 * * * *\", true},\n\t\t{\"Mon Jul 9 15:40 2012\", \"0/15 * * * *\", false},\n\n\t\t// Every fifteen minutes, starting at 5 minutes.\n\t\t{\"Mon Jul 9 15:05 2012\", \"5/15 * * * *\", true},\n\t\t{\"Mon Jul 9 15:20 2012\", \"5/15 * * * *\", true},\n\t\t{\"Mon Jul 9 15:50 2012\", \"5/15 * * * *\", true},\n\n\t\t// Named months\n\t\t{\"Sun Jul 15 15:00 2012\", \"0/15 * * Jul *\", true},\n\t\t{\"Sun Jul 15 15:00 2012\", \"0/15 * * Jun *\", false},\n\n\t\t// Everything set.\n\t\t{\"Sun Jul 15 08:30 2012\", \"30 08 ? Jul Sun\", true},\n\t\t{\"Sun Jul 15 08:30 2012\", \"30 08 15 Jul ?\", true},\n\t\t{\"Mon Jul 16 08:30 2012\", \"30 08 ? Jul Sun\", false},\n\t\t{\"Mon Jul 16 08:30 2012\", \"30 08 15 Jul ?\", false},\n\n\t\t// Predefined schedules\n\t\t{\"Mon Jul 9 15:00 2012\", \"@hourly\", true},\n\t\t{\"Mon Jul 9 15:04 2012\", \"@hourly\", false},\n\t\t{\"Mon Jul 9 15:00 2012\", \"@daily\", false},\n\t\t{\"Mon Jul 9 00:00 2012\", \"@daily\", true},\n\t\t{\"Mon Jul 9 00:00 2012\", \"@weekly\", false},\n\t\t{\"Sun Jul 8 00:00 2012\", \"@weekly\", true},\n\t\t{\"Sun Jul 8 01:00 2012\", \"@weekly\", false},\n\t\t{\"Sun Jul 8 00:00 2012\", \"@monthly\", false},\n\t\t{\"Sun Jul 1 00:00 2012\", \"@monthly\", true},\n\n\t\t// Test interaction of DOW and DOM.\n\t\t// If both are restricted, then only one needs to match.\n\t\t{\"Sun Jul 15 00:00 2012\", \"* * 1,15 * Sun\", true},\n\t\t{\"Fri Jun 15 00:00 2012\", \"* * 1,15 * Sun\", true},\n\t\t{\"Wed Aug 1 00:00 2012\", \"* * 1,15 * Sun\", true},\n\t\t{\"Sun Jul 15 00:00 2012\", \"* * */10 * Sun\", true}, // verifies #70\n\n\t\t// However, if one has a star, then both need to match.\n\t\t{\"Sun Jul 15 00:00 2012\", \"* * * * Mon\", false},\n\t\t{\"Mon Jul 9 00:00 2012\", \"* * 1,15 * *\", false},\n\t\t{\"Sun Jul 15 00:00 2012\", \"* * 1,15 * *\", true},\n\t\t{\"Sun Jul 15 00:00 2012\", \"* * */2 * Sun\", true},\n\t}\n\n\tfor _, test := range tests {\n\t\tsched, err := ParseStandard(test.spec)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tactual := sched.Next(getTime(test.time).Add(-1 * time.Second))\n\t\texpected := getTime(test.time)\n\t\tif test.expected && expected != actual || !test.expected && expected == actual {\n\t\t\tt.Errorf(\"Fail evaluating %s on %s: (expected) %s != %s (actual)\",\n\t\t\t\ttest.spec, test.time, expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestNext(t *testing.T) {\n\truns := []struct {\n\t\ttime, spec string\n\t\texpected   string\n\t}{\n\t\t// Simple cases\n\t\t{\"Mon Jul 9 14:45 2012\", \"0 0/15 * * * *\", \"Mon Jul 9 15:00 2012\"},\n\t\t{\"Mon Jul 9 14:59 2012\", \"0 0/15 * * * *\", \"Mon Jul 9 15:00 2012\"},\n\t\t{\"Mon Jul 9 14:59:59 2012\", \"0 0/15 * * * *\", \"Mon Jul 9 15:00 2012\"},\n\n\t\t// Wrap around hours\n\t\t{\"Mon Jul 9 15:45 2012\", \"0 20-35/15 * * * *\", \"Mon Jul 9 16:20 2012\"},\n\n\t\t// Wrap around days\n\t\t{\"Mon Jul 9 23:46 2012\", \"0 */15 * * * *\", \"Tue Jul 10 00:00 2012\"},\n\t\t{\"Mon Jul 9 23:45 2012\", \"0 20-35/15 * * * *\", \"Tue Jul 10 00:20 2012\"},\n\t\t{\"Mon Jul 9 23:35:51 2012\", \"15/35 20-35/15 * * * *\", \"Tue Jul 10 00:20:15 2012\"},\n\t\t{\"Mon Jul 9 23:35:51 2012\", \"15/35 20-35/15 1/2 * * *\", \"Tue Jul 10 01:20:15 2012\"},\n\t\t{\"Mon Jul 9 23:35:51 2012\", \"15/35 20-35/15 10-12 * * *\", \"Tue Jul 10 10:20:15 2012\"},\n\n\t\t{\"Mon Jul 9 23:35:51 2012\", \"15/35 20-35/15 1/2 */2 * *\", \"Thu Jul 11 01:20:15 2012\"},\n\t\t{\"Mon Jul 9 23:35:51 2012\", \"15/35 20-35/15 * 9-20 * *\", \"Wed Jul 10 00:20:15 2012\"},\n\t\t{\"Mon Jul 9 23:35:51 2012\", \"15/35 20-35/15 * 9-20 Jul *\", \"Wed Jul 10 00:20:15 2012\"},\n\n\t\t// Wrap around months\n\t\t{\"Mon Jul 9 23:35 2012\", \"0 0 0 9 Apr-Oct ?\", \"Thu Aug 9 00:00 2012\"},\n\t\t{\"Mon Jul 9 23:35 2012\", \"0 0 0 */5 Apr,Aug,Oct Mon\", \"Tue Aug 1 00:00 2012\"},\n\t\t{\"Mon Jul 9 23:35 2012\", \"0 0 0 */5 Oct Mon\", \"Mon Oct 1 00:00 2012\"},\n\n\t\t// Wrap around years\n\t\t{\"Mon Jul 9 23:35 2012\", \"0 0 0 * Feb Mon\", \"Mon Feb 4 00:00 2013\"},\n\t\t{\"Mon Jul 9 23:35 2012\", \"0 0 0 * Feb Mon/2\", \"Fri Feb 1 00:00 2013\"},\n\n\t\t// Wrap around minute, hour, day, month, and year\n\t\t{\"Mon Dec 31 23:59:45 2012\", \"0 * * * * *\", \"Tue Jan 1 00:00:00 2013\"},\n\n\t\t// Leap year\n\t\t{\"Mon Jul 9 23:35 2012\", \"0 0 0 29 Feb ?\", \"Mon Feb 29 00:00 2016\"},\n\n\t\t// Daylight savings time 2am EST (-5) -> 3am EDT (-4)\n\t\t{\"2012-03-11T00:00:00-0500\", \"TZ=America/New_York 0 30 2 11 Mar ?\", \"2013-03-11T02:30:00-0400\"},\n\n\t\t// hourly job\n\t\t{\"2012-03-11T00:00:00-0500\", \"TZ=America/New_York 0 0 * * * ?\", \"2012-03-11T01:00:00-0500\"},\n\t\t{\"2012-03-11T01:00:00-0500\", \"TZ=America/New_York 0 0 * * * ?\", \"2012-03-11T03:00:00-0400\"},\n\t\t{\"2012-03-11T03:00:00-0400\", \"TZ=America/New_York 0 0 * * * ?\", \"2012-03-11T04:00:00-0400\"},\n\t\t{\"2012-03-11T04:00:00-0400\", \"TZ=America/New_York 0 0 * * * ?\", \"2012-03-11T05:00:00-0400\"},\n\n\t\t// hourly job using CRON_TZ\n\t\t{\"2012-03-11T00:00:00-0500\", \"CRON_TZ=America/New_York 0 0 * * * ?\", \"2012-03-11T01:00:00-0500\"},\n\t\t{\"2012-03-11T01:00:00-0500\", \"CRON_TZ=America/New_York 0 0 * * * ?\", \"2012-03-11T03:00:00-0400\"},\n\t\t{\"2012-03-11T03:00:00-0400\", \"CRON_TZ=America/New_York 0 0 * * * ?\", \"2012-03-11T04:00:00-0400\"},\n\t\t{\"2012-03-11T04:00:00-0400\", \"CRON_TZ=America/New_York 0 0 * * * ?\", \"2012-03-11T05:00:00-0400\"},\n\n\t\t// 1am nightly job\n\t\t{\"2012-03-11T00:00:00-0500\", \"TZ=America/New_York 0 0 1 * * ?\", \"2012-03-11T01:00:00-0500\"},\n\t\t{\"2012-03-11T01:00:00-0500\", \"TZ=America/New_York 0 0 1 * * ?\", \"2012-03-12T01:00:00-0400\"},\n\n\t\t// 2am nightly job (skipped)\n\t\t{\"2012-03-11T00:00:00-0500\", \"TZ=America/New_York 0 0 2 * * ?\", \"2012-03-12T02:00:00-0400\"},\n\n\t\t// Daylight savings time 2am EDT (-4) => 1am EST (-5)\n\t\t{\"2012-11-04T00:00:00-0400\", \"TZ=America/New_York 0 30 2 04 Nov ?\", \"2012-11-04T02:30:00-0500\"},\n\t\t{\"2012-11-04T01:45:00-0400\", \"TZ=America/New_York 0 30 1 04 Nov ?\", \"2012-11-04T01:30:00-0500\"},\n\n\t\t// hourly job\n\t\t{\"2012-11-04T00:00:00-0400\", \"TZ=America/New_York 0 0 * * * ?\", \"2012-11-04T01:00:00-0400\"},\n\t\t{\"2012-11-04T01:00:00-0400\", \"TZ=America/New_York 0 0 * * * ?\", \"2012-11-04T01:00:00-0500\"},\n\t\t{\"2012-11-04T01:00:00-0500\", \"TZ=America/New_York 0 0 * * * ?\", \"2012-11-04T02:00:00-0500\"},\n\n\t\t// 1am nightly job (runs twice)\n\t\t{\"2012-11-04T00:00:00-0400\", \"TZ=America/New_York 0 0 1 * * ?\", \"2012-11-04T01:00:00-0400\"},\n\t\t{\"2012-11-04T01:00:00-0400\", \"TZ=America/New_York 0 0 1 * * ?\", \"2012-11-04T01:00:00-0500\"},\n\t\t{\"2012-11-04T01:00:00-0500\", \"TZ=America/New_York 0 0 1 * * ?\", \"2012-11-05T01:00:00-0500\"},\n\n\t\t// 2am nightly job\n\t\t{\"2012-11-04T00:00:00-0400\", \"TZ=America/New_York 0 0 2 * * ?\", \"2012-11-04T02:00:00-0500\"},\n\t\t{\"2012-11-04T02:00:00-0500\", \"TZ=America/New_York 0 0 2 * * ?\", \"2012-11-05T02:00:00-0500\"},\n\n\t\t// 3am nightly job\n\t\t{\"2012-11-04T00:00:00-0400\", \"TZ=America/New_York 0 0 3 * * ?\", \"2012-11-04T03:00:00-0500\"},\n\t\t{\"2012-11-04T03:00:00-0500\", \"TZ=America/New_York 0 0 3 * * ?\", \"2012-11-05T03:00:00-0500\"},\n\n\t\t// hourly job\n\t\t{\"TZ=America/New_York 2012-11-04T00:00:00-0400\", \"0 0 * * * ?\", \"2012-11-04T01:00:00-0400\"},\n\t\t{\"TZ=America/New_York 2012-11-04T01:00:00-0400\", \"0 0 * * * ?\", \"2012-11-04T01:00:00-0500\"},\n\t\t{\"TZ=America/New_York 2012-11-04T01:00:00-0500\", \"0 0 * * * ?\", \"2012-11-04T02:00:00-0500\"},\n\n\t\t// 1am nightly job (runs twice)\n\t\t{\"TZ=America/New_York 2012-11-04T00:00:00-0400\", \"0 0 1 * * ?\", \"2012-11-04T01:00:00-0400\"},\n\t\t{\"TZ=America/New_York 2012-11-04T01:00:00-0400\", \"0 0 1 * * ?\", \"2012-11-04T01:00:00-0500\"},\n\t\t{\"TZ=America/New_York 2012-11-04T01:00:00-0500\", \"0 0 1 * * ?\", \"2012-11-05T01:00:00-0500\"},\n\n\t\t// 2am nightly job\n\t\t{\"TZ=America/New_York 2012-11-04T00:00:00-0400\", \"0 0 2 * * ?\", \"2012-11-04T02:00:00-0500\"},\n\t\t{\"TZ=America/New_York 2012-11-04T02:00:00-0500\", \"0 0 2 * * ?\", \"2012-11-05T02:00:00-0500\"},\n\n\t\t// 3am nightly job\n\t\t{\"TZ=America/New_York 2012-11-04T00:00:00-0400\", \"0 0 3 * * ?\", \"2012-11-04T03:00:00-0500\"},\n\t\t{\"TZ=America/New_York 2012-11-04T03:00:00-0500\", \"0 0 3 * * ?\", \"2012-11-05T03:00:00-0500\"},\n\n\t\t// Unsatisfiable\n\t\t{\"Mon Jul 9 23:35 2012\", \"0 0 0 30 Feb ?\", \"\"},\n\t\t{\"Mon Jul 9 23:35 2012\", \"0 0 0 31 Apr ?\", \"\"},\n\n\t\t// Monthly job\n\t\t{\"TZ=America/New_York 2012-11-04T00:00:00-0400\", \"0 0 3 3 * ?\", \"2012-12-03T03:00:00-0500\"},\n\n\t\t// Test the scenario of DST resulting in midnight not being a valid time.\n\t\t// https://github.com/robfig/cron/issues/157\n\t\t{\"2018-10-17T05:00:00-0400\", \"TZ=America/Sao_Paulo 0 0 9 10 * ?\", \"2018-11-10T06:00:00-0500\"},\n\t\t{\"2018-02-14T05:00:00-0500\", \"TZ=America/Sao_Paulo 0 0 9 22 * ?\", \"2018-02-22T07:00:00-0500\"},\n\t}\n\n\tfor _, c := range runs {\n\t\tsched, err := secondParser.Parse(c.spec)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tactual := sched.Next(getTime(c.time))\n\t\texpected := getTime(c.expected)\n\t\tif !actual.Equal(expected) {\n\t\t\tt.Errorf(\"%s, \\\"%s\\\": (expected) %v != %v (actual)\", c.time, c.spec, expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestErrors(t *testing.T) {\n\tinvalidSpecs := []string{\n\t\t\"xyz\",\n\t\t\"60 0 * * *\",\n\t\t\"0 60 * * *\",\n\t\t\"0 0 * * XYZ\",\n\t}\n\tfor _, spec := range invalidSpecs {\n\t\t_, err := ParseStandard(spec)\n\t\tif err == nil {\n\t\t\tt.Error(\"expected an error parsing: \", spec)\n\t\t}\n\t}\n}\n\nfunc getTime(value string) time.Time {\n\tif value == \"\" {\n\t\treturn time.Time{}\n\t}\n\n\tvar location = time.Local\n\tif strings.HasPrefix(value, \"TZ=\") {\n\t\tparts := strings.Fields(value)\n\t\tloc, err := time.LoadLocation(parts[0][len(\"TZ=\"):])\n\t\tif err != nil {\n\t\t\tpanic(\"could not parse location:\" + err.Error())\n\t\t}\n\t\tlocation = loc\n\t\tvalue = parts[1]\n\t}\n\n\tvar layouts = []string{\n\t\t\"Mon Jan 2 15:04 2006\",\n\t\t\"Mon Jan 2 15:04:05 2006\",\n\t}\n\tfor _, layout := range layouts {\n\t\tif t, err := time.ParseInLocation(layout, value, location); err == nil {\n\t\t\treturn t\n\t\t}\n\t}\n\tif t, err := time.ParseInLocation(\"2006-01-02T15:04:05-0700\", value, location); err == nil {\n\t\treturn t\n\t}\n\tpanic(\"could not parse time value \" + value)\n}\n\nfunc TestNextWithTz(t *testing.T) {\n\truns := []struct {\n\t\ttime, spec string\n\t\texpected   string\n\t}{\n\t\t// Failing tests\n\t\t{\"2016-01-03T13:09:03+0530\", \"14 14 * * *\", \"2016-01-03T14:14:00+0530\"},\n\t\t{\"2016-01-03T04:09:03+0530\", \"14 14 * * ?\", \"2016-01-03T14:14:00+0530\"},\n\n\t\t// Passing tests\n\t\t{\"2016-01-03T14:09:03+0530\", \"14 14 * * *\", \"2016-01-03T14:14:00+0530\"},\n\t\t{\"2016-01-03T14:00:00+0530\", \"14 14 * * ?\", \"2016-01-03T14:14:00+0530\"},\n\t}\n\tfor _, c := range runs {\n\t\tsched, err := ParseStandard(c.spec)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tactual := sched.Next(getTimeTZ(c.time))\n\t\texpected := getTimeTZ(c.expected)\n\t\tif !actual.Equal(expected) {\n\t\t\tt.Errorf(\"%s, \\\"%s\\\": (expected) %v != %v (actual)\", c.time, c.spec, expected, actual)\n\t\t}\n\t}\n}\n\nfunc getTimeTZ(value string) time.Time {\n\tif value == \"\" {\n\t\treturn time.Time{}\n\t}\n\tt, err := time.Parse(\"Mon Jan 2 15:04 2006\", value)\n\tif err != nil {\n\t\tt, err = time.Parse(\"Mon Jan 2 15:04:05 2006\", value)\n\t\tif err != nil {\n\t\t\tt, err = time.Parse(\"2006-01-02T15:04:05-0700\", value)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn t\n}\n\n// https://github.com/robfig/cron/issues/144\nfunc TestSlash0NoHang(t *testing.T) {\n\tschedule := \"TZ=America/New_York 15/0 * * * *\"\n\t_, err := ParseStandard(schedule)\n\tif err == nil {\n\t\tt.Error(\"expected an error on 0 increment\")\n\t}\n}\n"
  }
]