cron_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. package cron
  2. import (
  3. "fmt"
  4. "sync"
  5. "testing"
  6. "time"
  7. )
  8. // Many tests schedule a job for every second, and then wait at most a second
  9. // for it to run. This amount is just slightly larger than 1 second to
  10. // compensate for a few milliseconds of runtime.
  11. const OneSecond = 1*time.Second + 10*time.Millisecond
  12. func TestFuncPanicRecovery(t *testing.T) {
  13. cron := New()
  14. cron.Start()
  15. defer cron.Stop()
  16. cron.AddFunc("* * * * * ?", func() { panic("YOLO") })
  17. select {
  18. case <-time.After(OneSecond):
  19. return
  20. }
  21. }
  22. type DummyJob struct{}
  23. func (d DummyJob) Run() {
  24. panic("YOLO")
  25. }
  26. func TestJobPanicRecovery(t *testing.T) {
  27. var job DummyJob
  28. cron := New()
  29. cron.Start()
  30. defer cron.Stop()
  31. cron.AddJob("* * * * * ?", job)
  32. select {
  33. case <-time.After(OneSecond):
  34. return
  35. }
  36. }
  37. // Start and stop cron with no entries.
  38. func TestNoEntries(t *testing.T) {
  39. cron := New()
  40. cron.Start()
  41. select {
  42. case <-time.After(OneSecond):
  43. t.Fatal("expected cron will be stopped immediately")
  44. case <-stop(cron):
  45. }
  46. }
  47. // Start, stop, then add an entry. Verify entry doesn't run.
  48. func TestStopCausesJobsToNotRun(t *testing.T) {
  49. wg := &sync.WaitGroup{}
  50. wg.Add(1)
  51. cron := New()
  52. cron.Start()
  53. cron.Stop()
  54. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  55. select {
  56. case <-time.After(OneSecond):
  57. // No job ran!
  58. case <-wait(wg):
  59. t.Fatal("expected stopped cron does not run any job")
  60. }
  61. }
  62. // Add a job, start cron, expect it runs.
  63. func TestAddBeforeRunning(t *testing.T) {
  64. wg := &sync.WaitGroup{}
  65. wg.Add(1)
  66. cron := New()
  67. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  68. cron.Start()
  69. defer cron.Stop()
  70. // Give cron 2 seconds to run our job (which is always activated).
  71. select {
  72. case <-time.After(OneSecond):
  73. t.Fatal("expected job runs")
  74. case <-wait(wg):
  75. }
  76. }
  77. // Start cron, add a job, expect it runs.
  78. func TestAddWhileRunning(t *testing.T) {
  79. wg := &sync.WaitGroup{}
  80. wg.Add(1)
  81. cron := New()
  82. cron.Start()
  83. defer cron.Stop()
  84. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  85. select {
  86. case <-time.After(OneSecond):
  87. t.Fatal("expected job runs")
  88. case <-wait(wg):
  89. }
  90. }
  91. // Test for #34. Adding a job after calling start results in multiple job invocations
  92. func TestAddWhileRunningWithDelay(t *testing.T) {
  93. cron := New()
  94. cron.Start()
  95. defer cron.Stop()
  96. time.Sleep(5 * time.Second)
  97. var calls = 0
  98. cron.AddFunc("* * * * * *", func() { calls += 1 })
  99. <-time.After(OneSecond)
  100. if calls != 1 {
  101. t.Errorf("called %d times, expected 1\n", calls)
  102. }
  103. }
  104. // Test timing with Entries.
  105. func TestSnapshotEntries(t *testing.T) {
  106. wg := &sync.WaitGroup{}
  107. wg.Add(1)
  108. cron := New()
  109. cron.AddFunc("@every 2s", func() { wg.Done() })
  110. cron.Start()
  111. defer cron.Stop()
  112. // Cron should fire in 2 seconds. After 1 second, call Entries.
  113. select {
  114. case <-time.After(OneSecond):
  115. cron.Entries()
  116. }
  117. // Even though Entries was called, the cron should fire at the 2 second mark.
  118. select {
  119. case <-time.After(OneSecond):
  120. t.Error("expected job runs at 2 second mark")
  121. case <-wait(wg):
  122. }
  123. }
  124. // Test that the entries are correctly sorted.
  125. // Add a bunch of long-in-the-future entries, and an immediate entry, and ensure
  126. // that the immediate entry runs immediately.
  127. // Also: Test that multiple jobs run in the same instant.
  128. func TestMultipleEntries(t *testing.T) {
  129. wg := &sync.WaitGroup{}
  130. wg.Add(2)
  131. cron := New()
  132. cron.AddFunc("0 0 0 1 1 ?", func() {})
  133. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  134. cron.AddFunc("0 0 0 31 12 ?", func() {})
  135. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  136. cron.Start()
  137. defer cron.Stop()
  138. select {
  139. case <-time.After(OneSecond):
  140. t.Error("expected job run in proper order")
  141. case <-wait(wg):
  142. }
  143. }
  144. // Test running the same job twice.
  145. func TestRunningJobTwice(t *testing.T) {
  146. wg := &sync.WaitGroup{}
  147. wg.Add(2)
  148. cron := New()
  149. cron.AddFunc("0 0 0 1 1 ?", func() {})
  150. cron.AddFunc("0 0 0 31 12 ?", func() {})
  151. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  152. cron.Start()
  153. defer cron.Stop()
  154. select {
  155. case <-time.After(2 * OneSecond):
  156. t.Error("expected job fires 2 times")
  157. case <-wait(wg):
  158. }
  159. }
  160. func TestRunningMultipleSchedules(t *testing.T) {
  161. wg := &sync.WaitGroup{}
  162. wg.Add(2)
  163. cron := New()
  164. cron.AddFunc("0 0 0 1 1 ?", func() {})
  165. cron.AddFunc("0 0 0 31 12 ?", func() {})
  166. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  167. cron.Schedule(Every(time.Minute), FuncJob(func() {}))
  168. cron.Schedule(Every(time.Second), FuncJob(func() { wg.Done() }))
  169. cron.Schedule(Every(time.Hour), FuncJob(func() {}))
  170. cron.Start()
  171. defer cron.Stop()
  172. select {
  173. case <-time.After(2 * OneSecond):
  174. t.Error("expected job fires 2 times")
  175. case <-wait(wg):
  176. }
  177. }
  178. // Test that the cron is run in the local time zone (as opposed to UTC).
  179. func TestLocalTimezone(t *testing.T) {
  180. wg := &sync.WaitGroup{}
  181. wg.Add(2)
  182. now := time.Now()
  183. spec := fmt.Sprintf("%d,%d %d %d %d %d ?",
  184. now.Second()+1, now.Second()+2, now.Minute(), now.Hour(), now.Day(), now.Month())
  185. cron := New()
  186. cron.AddFunc(spec, func() { wg.Done() })
  187. cron.Start()
  188. defer cron.Stop()
  189. select {
  190. case <-time.After(OneSecond * 2):
  191. t.Error("expected job fires 2 times")
  192. case <-wait(wg):
  193. }
  194. }
  195. // Test that the cron is run in the given time zone (as opposed to local).
  196. func TestNonLocalTimezone(t *testing.T) {
  197. wg := &sync.WaitGroup{}
  198. wg.Add(2)
  199. loc, err := time.LoadLocation("Atlantic/Cape_Verde")
  200. if err != nil {
  201. fmt.Printf("Failed to load time zone Atlantic/Cape_Verde: %+v", err)
  202. t.Fail()
  203. }
  204. now := time.Now().In(loc)
  205. spec := fmt.Sprintf("%d,%d %d %d %d %d ?",
  206. now.Second()+1, now.Second()+2, now.Minute(), now.Hour(), now.Day(), now.Month())
  207. cron := NewWithLocation(loc)
  208. cron.AddFunc(spec, func() { wg.Done() })
  209. cron.Start()
  210. defer cron.Stop()
  211. select {
  212. case <-time.After(OneSecond * 2):
  213. t.Error("expected job fires 2 times")
  214. case <-wait(wg):
  215. }
  216. }
  217. // Test that calling stop before start silently returns without
  218. // blocking the stop channel.
  219. func TestStopWithoutStart(t *testing.T) {
  220. cron := New()
  221. cron.Stop()
  222. }
  223. type testJob struct {
  224. wg *sync.WaitGroup
  225. name string
  226. }
  227. func (t testJob) Run() {
  228. t.wg.Done()
  229. }
  230. // Test that adding an invalid job spec returns an error
  231. func TestInvalidJobSpec(t *testing.T) {
  232. cron := New()
  233. err := cron.AddJob("this will not parse", nil)
  234. if err == nil {
  235. t.Errorf("expected an error with invalid spec, got nil")
  236. }
  237. }
  238. // Test blocking run method behaves as Start()
  239. func TestBlockingRun(t *testing.T) {
  240. wg := &sync.WaitGroup{}
  241. wg.Add(1)
  242. cron := New()
  243. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  244. var unblockChan = make(chan struct{})
  245. go func() {
  246. cron.Run()
  247. close(unblockChan)
  248. }()
  249. defer cron.Stop()
  250. select {
  251. case <-time.After(OneSecond):
  252. t.Error("expected job fires")
  253. case <-unblockChan:
  254. t.Error("expected that Run() blocks")
  255. case <-wait(wg):
  256. }
  257. }
  258. // Test that double-running is a no-op
  259. func TestStartNoop(t *testing.T) {
  260. var tickChan = make(chan struct{}, 2)
  261. cron := New()
  262. cron.AddFunc("* * * * * ?", func() {
  263. tickChan <- struct{}{}
  264. })
  265. cron.Start()
  266. defer cron.Stop()
  267. // Wait for the first firing to ensure the runner is going
  268. <-tickChan
  269. cron.Start()
  270. <-tickChan
  271. // Fail if this job fires again in a short period, indicating a double-run
  272. select {
  273. case <-time.After(time.Millisecond):
  274. case <-tickChan:
  275. t.Error("expected job fires exactly twice")
  276. }
  277. }
  278. // Simple test using Runnables.
  279. func TestJob(t *testing.T) {
  280. wg := &sync.WaitGroup{}
  281. wg.Add(1)
  282. cron := New()
  283. cron.AddJob("0 0 0 30 Feb ?", testJob{wg, "job0"})
  284. cron.AddJob("0 0 0 1 1 ?", testJob{wg, "job1"})
  285. cron.AddJob("* * * * * ?", testJob{wg, "job2"})
  286. cron.AddJob("1 0 0 1 1 ?", testJob{wg, "job3"})
  287. cron.Schedule(Every(5*time.Second+5*time.Nanosecond), testJob{wg, "job4"})
  288. cron.Schedule(Every(5*time.Minute), testJob{wg, "job5"})
  289. cron.Start()
  290. defer cron.Stop()
  291. select {
  292. case <-time.After(OneSecond):
  293. t.FailNow()
  294. case <-wait(wg):
  295. }
  296. // Ensure the entries are in the right order.
  297. expecteds := []string{"job2", "job4", "job5", "job1", "job3", "job0"}
  298. var actuals []string
  299. for _, entry := range cron.Entries() {
  300. actuals = append(actuals, entry.Job.(testJob).name)
  301. }
  302. for i, expected := range expecteds {
  303. if actuals[i] != expected {
  304. t.Fatalf("Jobs not in the right order. (expected) %s != %s (actual)", expecteds, actuals)
  305. }
  306. }
  307. }
  308. type ZeroSchedule struct{}
  309. func (*ZeroSchedule) Next(time.Time) time.Time {
  310. return time.Time{}
  311. }
  312. // Tests that job without time does not run
  313. func TestJobWithZeroTimeDoesNotRun(t *testing.T) {
  314. cron := New()
  315. calls := 0
  316. cron.AddFunc("* * * * * *", func() { calls += 1 })
  317. cron.Schedule(new(ZeroSchedule), FuncJob(func() { t.Error("expected zero task will not run") }))
  318. cron.Start()
  319. defer cron.Stop()
  320. <-time.After(OneSecond)
  321. if calls != 1 {
  322. t.Errorf("called %d times, expected 1\n", calls)
  323. }
  324. }
  325. func wait(wg *sync.WaitGroup) chan bool {
  326. ch := make(chan bool)
  327. go func() {
  328. wg.Wait()
  329. ch <- true
  330. }()
  331. return ch
  332. }
  333. func stop(cron *Cron) chan bool {
  334. ch := make(chan bool)
  335. go func() {
  336. cron.Stop()
  337. ch <- true
  338. }()
  339. return ch
  340. }