cron_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. package cron
  2. import (
  3. "bytes"
  4. "fmt"
  5. "log"
  6. "strings"
  7. "sync"
  8. "sync/atomic"
  9. "testing"
  10. "time"
  11. )
  12. // Many tests schedule a job for every second, and then wait at most a second
  13. // for it to run. This amount is just slightly larger than 1 second to
  14. // compensate for a few milliseconds of runtime.
  15. const OneSecond = 1*time.Second + 50*time.Millisecond
  16. type syncWriter struct {
  17. wr bytes.Buffer
  18. m sync.Mutex
  19. }
  20. func (sw *syncWriter) Write(data []byte) (n int, err error) {
  21. sw.m.Lock()
  22. n, err = sw.wr.Write(data)
  23. sw.m.Unlock()
  24. return
  25. }
  26. func (sw *syncWriter) String() string {
  27. sw.m.Lock()
  28. defer sw.m.Unlock()
  29. return sw.wr.String()
  30. }
  31. func newBufLogger(sw *syncWriter) Logger {
  32. return PrintfLogger(log.New(sw, "", log.LstdFlags))
  33. }
  34. func TestFuncPanicRecovery(t *testing.T) {
  35. var buf syncWriter
  36. cron := New(WithParser(secondParser),
  37. WithChain(Recover(newBufLogger(&buf))))
  38. cron.Start()
  39. defer cron.Stop()
  40. cron.AddFunc("* * * * * ?", func() {
  41. panic("YOLO")
  42. })
  43. select {
  44. case <-time.After(OneSecond):
  45. if !strings.Contains(buf.String(), "YOLO") {
  46. t.Error("expected a panic to be logged, got none")
  47. }
  48. return
  49. }
  50. }
  51. type DummyJob struct{}
  52. func (d DummyJob) Run() {
  53. panic("YOLO")
  54. }
  55. func TestJobPanicRecovery(t *testing.T) {
  56. var job DummyJob
  57. var buf syncWriter
  58. cron := New(WithParser(secondParser),
  59. WithChain(Recover(newBufLogger(&buf))))
  60. cron.Start()
  61. defer cron.Stop()
  62. cron.AddJob("* * * * * ?", job)
  63. select {
  64. case <-time.After(OneSecond):
  65. if !strings.Contains(buf.String(), "YOLO") {
  66. t.Error("expected a panic to be logged, got none")
  67. }
  68. return
  69. }
  70. }
  71. // Start and stop cron with no entries.
  72. func TestNoEntries(t *testing.T) {
  73. cron := newWithSeconds()
  74. cron.Start()
  75. select {
  76. case <-time.After(OneSecond):
  77. t.Fatal("expected cron will be stopped immediately")
  78. case <-stop(cron):
  79. }
  80. }
  81. // Start, stop, then add an entry. Verify entry doesn't run.
  82. func TestStopCausesJobsToNotRun(t *testing.T) {
  83. wg := &sync.WaitGroup{}
  84. wg.Add(1)
  85. cron := newWithSeconds()
  86. cron.Start()
  87. cron.Stop()
  88. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  89. select {
  90. case <-time.After(OneSecond):
  91. // No job ran!
  92. case <-wait(wg):
  93. t.Fatal("expected stopped cron does not run any job")
  94. }
  95. }
  96. // Add a job, start cron, expect it runs.
  97. func TestAddBeforeRunning(t *testing.T) {
  98. wg := &sync.WaitGroup{}
  99. wg.Add(1)
  100. cron := newWithSeconds()
  101. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  102. cron.Start()
  103. defer cron.Stop()
  104. // Give cron 2 seconds to run our job (which is always activated).
  105. select {
  106. case <-time.After(OneSecond):
  107. t.Fatal("expected job runs")
  108. case <-wait(wg):
  109. }
  110. }
  111. // Start cron, add a job, expect it runs.
  112. func TestAddWhileRunning(t *testing.T) {
  113. wg := &sync.WaitGroup{}
  114. wg.Add(1)
  115. cron := newWithSeconds()
  116. cron.Start()
  117. defer cron.Stop()
  118. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  119. select {
  120. case <-time.After(OneSecond):
  121. t.Fatal("expected job runs")
  122. case <-wait(wg):
  123. }
  124. }
  125. // Test for #34. Adding a job after calling start results in multiple job invocations
  126. func TestAddWhileRunningWithDelay(t *testing.T) {
  127. cron := newWithSeconds()
  128. cron.Start()
  129. defer cron.Stop()
  130. time.Sleep(5 * time.Second)
  131. var calls int64
  132. cron.AddFunc("* * * * * *", func() { atomic.AddInt64(&calls, 1) })
  133. <-time.After(OneSecond)
  134. if atomic.LoadInt64(&calls) != 1 {
  135. t.Errorf("called %d times, expected 1\n", calls)
  136. }
  137. }
  138. // Add a job, remove a job, start cron, expect nothing runs.
  139. func TestRemoveBeforeRunning(t *testing.T) {
  140. wg := &sync.WaitGroup{}
  141. wg.Add(1)
  142. cron := newWithSeconds()
  143. id, _ := cron.AddFunc("* * * * * ?", func() { wg.Done() })
  144. cron.Remove(id)
  145. cron.Start()
  146. defer cron.Stop()
  147. select {
  148. case <-time.After(OneSecond):
  149. // Success, shouldn't run
  150. case <-wait(wg):
  151. t.FailNow()
  152. }
  153. }
  154. // Start cron, add a job, remove it, expect it doesn't run.
  155. func TestRemoveWhileRunning(t *testing.T) {
  156. wg := &sync.WaitGroup{}
  157. wg.Add(1)
  158. cron := newWithSeconds()
  159. cron.Start()
  160. defer cron.Stop()
  161. id, _ := cron.AddFunc("* * * * * ?", func() { wg.Done() })
  162. cron.Remove(id)
  163. select {
  164. case <-time.After(OneSecond):
  165. case <-wait(wg):
  166. t.FailNow()
  167. }
  168. }
  169. // Test timing with Entries.
  170. func TestSnapshotEntries(t *testing.T) {
  171. wg := &sync.WaitGroup{}
  172. wg.Add(1)
  173. cron := New()
  174. cron.AddFunc("@every 2s", func() { wg.Done() })
  175. cron.Start()
  176. defer cron.Stop()
  177. // Cron should fire in 2 seconds. After 1 second, call Entries.
  178. select {
  179. case <-time.After(OneSecond):
  180. cron.Entries()
  181. }
  182. // Even though Entries was called, the cron should fire at the 2 second mark.
  183. select {
  184. case <-time.After(OneSecond):
  185. t.Error("expected job runs at 2 second mark")
  186. case <-wait(wg):
  187. }
  188. }
  189. // Test that the entries are correctly sorted.
  190. // Add a bunch of long-in-the-future entries, and an immediate entry, and ensure
  191. // that the immediate entry runs immediately.
  192. // Also: Test that multiple jobs run in the same instant.
  193. func TestMultipleEntries(t *testing.T) {
  194. wg := &sync.WaitGroup{}
  195. wg.Add(2)
  196. cron := newWithSeconds()
  197. cron.AddFunc("0 0 0 1 1 ?", func() {})
  198. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  199. id1, _ := cron.AddFunc("* * * * * ?", func() { t.Fatal() })
  200. id2, _ := cron.AddFunc("* * * * * ?", func() { t.Fatal() })
  201. cron.AddFunc("0 0 0 31 12 ?", func() {})
  202. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  203. cron.Remove(id1)
  204. cron.Start()
  205. cron.Remove(id2)
  206. defer cron.Stop()
  207. select {
  208. case <-time.After(OneSecond):
  209. t.Error("expected job run in proper order")
  210. case <-wait(wg):
  211. }
  212. }
  213. // Test running the same job twice.
  214. func TestRunningJobTwice(t *testing.T) {
  215. wg := &sync.WaitGroup{}
  216. wg.Add(2)
  217. cron := newWithSeconds()
  218. cron.AddFunc("0 0 0 1 1 ?", func() {})
  219. cron.AddFunc("0 0 0 31 12 ?", func() {})
  220. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  221. cron.Start()
  222. defer cron.Stop()
  223. select {
  224. case <-time.After(2 * OneSecond):
  225. t.Error("expected job fires 2 times")
  226. case <-wait(wg):
  227. }
  228. }
  229. func TestRunningMultipleSchedules(t *testing.T) {
  230. wg := &sync.WaitGroup{}
  231. wg.Add(2)
  232. cron := newWithSeconds()
  233. cron.AddFunc("0 0 0 1 1 ?", func() {})
  234. cron.AddFunc("0 0 0 31 12 ?", func() {})
  235. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  236. cron.Schedule(Every(time.Minute), FuncJob(func() {}))
  237. cron.Schedule(Every(time.Second), FuncJob(func() { wg.Done() }))
  238. cron.Schedule(Every(time.Hour), FuncJob(func() {}))
  239. cron.Start()
  240. defer cron.Stop()
  241. select {
  242. case <-time.After(2 * OneSecond):
  243. t.Error("expected job fires 2 times")
  244. case <-wait(wg):
  245. }
  246. }
  247. // Test that the cron is run in the local time zone (as opposed to UTC).
  248. func TestLocalTimezone(t *testing.T) {
  249. wg := &sync.WaitGroup{}
  250. wg.Add(2)
  251. now := time.Now()
  252. // FIX: Issue #205
  253. // This calculation doesn't work in seconds 58 or 59.
  254. // Take the easy way out and sleep.
  255. if now.Second() >= 58 {
  256. time.Sleep(2 * time.Second)
  257. now = time.Now()
  258. }
  259. spec := fmt.Sprintf("%d,%d %d %d %d %d ?",
  260. now.Second()+1, now.Second()+2, now.Minute(), now.Hour(), now.Day(), now.Month())
  261. cron := newWithSeconds()
  262. cron.AddFunc(spec, func() { wg.Done() })
  263. cron.Start()
  264. defer cron.Stop()
  265. select {
  266. case <-time.After(OneSecond * 2):
  267. t.Error("expected job fires 2 times")
  268. case <-wait(wg):
  269. }
  270. }
  271. // Test that the cron is run in the given time zone (as opposed to local).
  272. func TestNonLocalTimezone(t *testing.T) {
  273. wg := &sync.WaitGroup{}
  274. wg.Add(2)
  275. loc, err := time.LoadLocation("Atlantic/Cape_Verde")
  276. if err != nil {
  277. fmt.Printf("Failed to load time zone Atlantic/Cape_Verde: %+v", err)
  278. t.Fail()
  279. }
  280. now := time.Now().In(loc)
  281. // FIX: Issue #205
  282. // This calculation doesn't work in seconds 58 or 59.
  283. // Take the easy way out and sleep.
  284. if now.Second() >= 58 {
  285. time.Sleep(2 * time.Second)
  286. now = time.Now().In(loc)
  287. }
  288. spec := fmt.Sprintf("%d,%d %d %d %d %d ?",
  289. now.Second()+1, now.Second()+2, now.Minute(), now.Hour(), now.Day(), now.Month())
  290. cron := New(WithLocation(loc), WithParser(secondParser))
  291. cron.AddFunc(spec, func() { wg.Done() })
  292. cron.Start()
  293. defer cron.Stop()
  294. select {
  295. case <-time.After(OneSecond * 2):
  296. t.Error("expected job fires 2 times")
  297. case <-wait(wg):
  298. }
  299. }
  300. // Test that calling stop before start silently returns without
  301. // blocking the stop channel.
  302. func TestStopWithoutStart(t *testing.T) {
  303. cron := New()
  304. cron.Stop()
  305. }
  306. type testJob struct {
  307. wg *sync.WaitGroup
  308. name string
  309. }
  310. func (t testJob) Run() {
  311. t.wg.Done()
  312. }
  313. // Test that adding an invalid job spec returns an error
  314. func TestInvalidJobSpec(t *testing.T) {
  315. cron := New()
  316. _, err := cron.AddJob("this will not parse", nil)
  317. if err == nil {
  318. t.Errorf("expected an error with invalid spec, got nil")
  319. }
  320. }
  321. // Test blocking run method behaves as Start()
  322. func TestBlockingRun(t *testing.T) {
  323. wg := &sync.WaitGroup{}
  324. wg.Add(1)
  325. cron := newWithSeconds()
  326. cron.AddFunc("* * * * * ?", func() { wg.Done() })
  327. var unblockChan = make(chan struct{})
  328. go func() {
  329. cron.Run()
  330. close(unblockChan)
  331. }()
  332. defer cron.Stop()
  333. select {
  334. case <-time.After(OneSecond):
  335. t.Error("expected job fires")
  336. case <-unblockChan:
  337. t.Error("expected that Run() blocks")
  338. case <-wait(wg):
  339. }
  340. }
  341. // Test that double-running is a no-op
  342. func TestStartNoop(t *testing.T) {
  343. var tickChan = make(chan struct{}, 2)
  344. cron := newWithSeconds()
  345. cron.AddFunc("* * * * * ?", func() {
  346. tickChan <- struct{}{}
  347. })
  348. cron.Start()
  349. defer cron.Stop()
  350. // Wait for the first firing to ensure the runner is going
  351. <-tickChan
  352. cron.Start()
  353. <-tickChan
  354. // Fail if this job fires again in a short period, indicating a double-run
  355. select {
  356. case <-time.After(time.Millisecond):
  357. case <-tickChan:
  358. t.Error("expected job fires exactly twice")
  359. }
  360. }
  361. // Simple test using Runnables.
  362. func TestJob(t *testing.T) {
  363. wg := &sync.WaitGroup{}
  364. wg.Add(1)
  365. cron := newWithSeconds()
  366. cron.AddJob("0 0 0 30 Feb ?", testJob{wg, "job0"})
  367. cron.AddJob("0 0 0 1 1 ?", testJob{wg, "job1"})
  368. job2, _ := cron.AddJob("* * * * * ?", testJob{wg, "job2"})
  369. cron.AddJob("1 0 0 1 1 ?", testJob{wg, "job3"})
  370. cron.Schedule(Every(5*time.Second+5*time.Nanosecond), testJob{wg, "job4"})
  371. job5 := cron.Schedule(Every(5*time.Minute), testJob{wg, "job5"})
  372. // Test getting an Entry pre-Start.
  373. if actualName := cron.Entry(job2).Job.(testJob).name; actualName != "job2" {
  374. t.Error("wrong job retrieved:", actualName)
  375. }
  376. if actualName := cron.Entry(job5).Job.(testJob).name; actualName != "job5" {
  377. t.Error("wrong job retrieved:", actualName)
  378. }
  379. cron.Start()
  380. defer cron.Stop()
  381. select {
  382. case <-time.After(OneSecond):
  383. t.FailNow()
  384. case <-wait(wg):
  385. }
  386. // Ensure the entries are in the right order.
  387. expecteds := []string{"job2", "job4", "job5", "job1", "job3", "job0"}
  388. var actuals []string
  389. for _, entry := range cron.Entries() {
  390. actuals = append(actuals, entry.Job.(testJob).name)
  391. }
  392. for i, expected := range expecteds {
  393. if actuals[i] != expected {
  394. t.Fatalf("Jobs not in the right order. (expected) %s != %s (actual)", expecteds, actuals)
  395. }
  396. }
  397. // Test getting Entries.
  398. if actualName := cron.Entry(job2).Job.(testJob).name; actualName != "job2" {
  399. t.Error("wrong job retrieved:", actualName)
  400. }
  401. if actualName := cron.Entry(job5).Job.(testJob).name; actualName != "job5" {
  402. t.Error("wrong job retrieved:", actualName)
  403. }
  404. }
  405. // Issue #206
  406. // Ensure that the next run of a job after removing an entry is accurate.
  407. func TestScheduleAfterRemoval(t *testing.T) {
  408. var wg1 sync.WaitGroup
  409. var wg2 sync.WaitGroup
  410. wg1.Add(1)
  411. wg2.Add(1)
  412. // The first time this job is run, set a timer and remove the other job
  413. // 750ms later. Correct behavior would be to still run the job again in
  414. // 250ms, but the bug would cause it to run instead 1s later.
  415. var calls int
  416. var mu sync.Mutex
  417. cron := newWithSeconds()
  418. hourJob := cron.Schedule(Every(time.Hour), FuncJob(func() {}))
  419. cron.Schedule(Every(time.Second), FuncJob(func() {
  420. mu.Lock()
  421. defer mu.Unlock()
  422. switch calls {
  423. case 0:
  424. wg1.Done()
  425. calls++
  426. case 1:
  427. time.Sleep(750 * time.Millisecond)
  428. cron.Remove(hourJob)
  429. calls++
  430. case 2:
  431. calls++
  432. wg2.Done()
  433. case 3:
  434. panic("unexpected 3rd call")
  435. }
  436. }))
  437. cron.Start()
  438. defer cron.Stop()
  439. // the first run might be any length of time 0 - 1s, since the schedule
  440. // rounds to the second. wait for the first run to true up.
  441. wg1.Wait()
  442. select {
  443. case <-time.After(2 * OneSecond):
  444. t.Error("expected job fires 2 times")
  445. case <-wait(&wg2):
  446. }
  447. }
  448. type ZeroSchedule struct{}
  449. func (*ZeroSchedule) Next(time.Time) time.Time {
  450. return time.Time{}
  451. }
  452. // Tests that job without time does not run
  453. func TestJobWithZeroTimeDoesNotRun(t *testing.T) {
  454. cron := newWithSeconds()
  455. var calls int64
  456. cron.AddFunc("* * * * * *", func() { atomic.AddInt64(&calls, 1) })
  457. cron.Schedule(new(ZeroSchedule), FuncJob(func() { t.Error("expected zero task will not run") }))
  458. cron.Start()
  459. defer cron.Stop()
  460. <-time.After(OneSecond)
  461. if atomic.LoadInt64(&calls) != 1 {
  462. t.Errorf("called %d times, expected 1\n", calls)
  463. }
  464. }
  465. func TestStopAndWait(t *testing.T) {
  466. t.Run("nothing running, returns immediately", func(t *testing.T) {
  467. cron := newWithSeconds()
  468. cron.Start()
  469. ctx := cron.Stop()
  470. select {
  471. case <-ctx.Done():
  472. case <-time.After(time.Millisecond):
  473. t.Error("context was not done immediately")
  474. }
  475. })
  476. t.Run("repeated calls to Stop", func(t *testing.T) {
  477. cron := newWithSeconds()
  478. cron.Start()
  479. _ = cron.Stop()
  480. time.Sleep(time.Millisecond)
  481. ctx := cron.Stop()
  482. select {
  483. case <-ctx.Done():
  484. case <-time.After(time.Millisecond):
  485. t.Error("context was not done immediately")
  486. }
  487. })
  488. t.Run("a couple fast jobs added, still returns immediately", func(t *testing.T) {
  489. cron := newWithSeconds()
  490. cron.AddFunc("* * * * * *", func() {})
  491. cron.Start()
  492. cron.AddFunc("* * * * * *", func() {})
  493. cron.AddFunc("* * * * * *", func() {})
  494. cron.AddFunc("* * * * * *", func() {})
  495. time.Sleep(time.Second)
  496. ctx := cron.Stop()
  497. select {
  498. case <-ctx.Done():
  499. case <-time.After(time.Millisecond):
  500. t.Error("context was not done immediately")
  501. }
  502. })
  503. t.Run("a couple fast jobs and a slow job added, waits for slow job", func(t *testing.T) {
  504. cron := newWithSeconds()
  505. cron.AddFunc("* * * * * *", func() {})
  506. cron.Start()
  507. cron.AddFunc("* * * * * *", func() { time.Sleep(2 * time.Second) })
  508. cron.AddFunc("* * * * * *", func() {})
  509. time.Sleep(time.Second)
  510. ctx := cron.Stop()
  511. // Verify that it is not done for at least 750ms
  512. select {
  513. case <-ctx.Done():
  514. t.Error("context was done too quickly immediately")
  515. case <-time.After(750 * time.Millisecond):
  516. // expected, because the job sleeping for 1 second is still running
  517. }
  518. // Verify that it IS done in the next 500ms (giving 250ms buffer)
  519. select {
  520. case <-ctx.Done():
  521. // expected
  522. case <-time.After(1500 * time.Millisecond):
  523. t.Error("context not done after job should have completed")
  524. }
  525. })
  526. t.Run("repeated calls to stop, waiting for completion and after", func(t *testing.T) {
  527. cron := newWithSeconds()
  528. cron.AddFunc("* * * * * *", func() {})
  529. cron.AddFunc("* * * * * *", func() { time.Sleep(2 * time.Second) })
  530. cron.Start()
  531. cron.AddFunc("* * * * * *", func() {})
  532. time.Sleep(time.Second)
  533. ctx := cron.Stop()
  534. ctx2 := cron.Stop()
  535. // Verify that it is not done for at least 1500ms
  536. select {
  537. case <-ctx.Done():
  538. t.Error("context was done too quickly immediately")
  539. case <-ctx2.Done():
  540. t.Error("context2 was done too quickly immediately")
  541. case <-time.After(1500 * time.Millisecond):
  542. // expected, because the job sleeping for 2 seconds is still running
  543. }
  544. // Verify that it IS done in the next 1s (giving 500ms buffer)
  545. select {
  546. case <-ctx.Done():
  547. // expected
  548. case <-time.After(time.Second):
  549. t.Error("context not done after job should have completed")
  550. }
  551. // Verify that ctx2 is also done.
  552. select {
  553. case <-ctx2.Done():
  554. // expected
  555. case <-time.After(time.Millisecond):
  556. t.Error("context2 not done even though context1 is")
  557. }
  558. // Verify that a new context retrieved from stop is immediately done.
  559. ctx3 := cron.Stop()
  560. select {
  561. case <-ctx3.Done():
  562. // expected
  563. case <-time.After(time.Millisecond):
  564. t.Error("context not done even when cron Stop is completed")
  565. }
  566. })
  567. }
  568. func TestMultiThreadedStartAndStop(t *testing.T) {
  569. cron := New()
  570. go cron.Run()
  571. time.Sleep(2 * time.Millisecond)
  572. cron.Stop()
  573. }
  574. func wait(wg *sync.WaitGroup) chan bool {
  575. ch := make(chan bool)
  576. go func() {
  577. wg.Wait()
  578. ch <- true
  579. }()
  580. return ch
  581. }
  582. func stop(cron *Cron) chan bool {
  583. ch := make(chan bool)
  584. go func() {
  585. cron.Stop()
  586. ch <- true
  587. }()
  588. return ch
  589. }
  590. // newWithSeconds returns a Cron with the seconds field enabled.
  591. func newWithSeconds() *Cron {
  592. return New(WithParser(secondParser), WithChain())
  593. }