timer.go 579 B

12345678910111213141516171819202122232425262728293031
  1. package cron
  2. import (
  3. "app.yhyue.com/moapp/jybase/common"
  4. "log"
  5. "strings"
  6. "time"
  7. )
  8. func CrontabByTimer(flag bool, c string, f func()) {
  9. array := strings.Split(c, ":")
  10. if len(array) != 2 {
  11. log.Fatalln("定时任务参数错误!", c)
  12. }
  13. if flag {
  14. go f()
  15. }
  16. now := time.Now()
  17. t := time.Date(now.Year(), now.Month(), now.Day(), common.IntAll(array[0]), common.IntAll(array[1]), 0, 0, time.Local)
  18. if t.Before(now) {
  19. t = t.AddDate(0, 0, 1)
  20. }
  21. timer := time.NewTimer(t.Sub(now))
  22. for {
  23. select {
  24. case <-timer.C:
  25. go f()
  26. timer.Reset(24 * time.Hour)
  27. }
  28. }
  29. }