task_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package toolbox
  15. import (
  16. "fmt"
  17. "sync"
  18. "testing"
  19. "time"
  20. )
  21. func TestParse(t *testing.T) {
  22. tk := NewTask("taska", "0/30 * * * * *", func() error { fmt.Println("hello world"); return nil })
  23. err := tk.Run()
  24. if err != nil {
  25. t.Fatal(err)
  26. }
  27. AddTask("taska", tk)
  28. StartTask()
  29. time.Sleep(6 * time.Second)
  30. StopTask()
  31. }
  32. func TestSpec(t *testing.T) {
  33. wg := &sync.WaitGroup{}
  34. wg.Add(2)
  35. tk1 := NewTask("tk1", "0 12 * * * *", func() error { fmt.Println("tk1"); return nil })
  36. tk2 := NewTask("tk2", "0,10,20 * * * * *", func() error { fmt.Println("tk2"); wg.Done(); return nil })
  37. tk3 := NewTask("tk3", "0 10 * * * *", func() error { fmt.Println("tk3"); wg.Done(); return nil })
  38. AddTask("tk1", tk1)
  39. AddTask("tk2", tk2)
  40. AddTask("tk3", tk3)
  41. StartTask()
  42. defer StopTask()
  43. select {
  44. case <-time.After(200 * time.Second):
  45. t.FailNow()
  46. case <-wait(wg):
  47. }
  48. }
  49. func wait(wg *sync.WaitGroup) chan bool {
  50. ch := make(chan bool)
  51. go func() {
  52. wg.Wait()
  53. ch <- true
  54. }()
  55. return ch
  56. }