智慧食堂
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

91 rader
1.9 KiB

  1. package task
  2. import (
  3. "applet/app/db"
  4. "applet/app/db/model"
  5. taskMd "applet/app/task/md"
  6. "fmt"
  7. "time"
  8. "applet/app/utils/logx"
  9. "github.com/robfig/cron/v3"
  10. "xorm.io/xorm"
  11. )
  12. var (
  13. timer *cron.Cron
  14. jobs = map[string]func(*xorm.Engine){}
  15. baseEntryId cron.EntryID
  16. entryIds []cron.EntryID
  17. taskCfgList *[]model.CronTask
  18. ch = make(chan int, 30)
  19. workerNum = 15 // 智盟跟单并发数量
  20. )
  21. func Init() {
  22. // 初始化任务列表initTasks()
  23. var err error
  24. timer = cron.New()
  25. // reload为初始化数据库方法
  26. if baseEntryId, err = timer.AddFunc("@every 30m", reload); err != nil {
  27. _ = logx.Fatal(err)
  28. }
  29. }
  30. func Run() {
  31. reload()
  32. timer.Start()
  33. _ = logx.Info("auto tasks running...")
  34. }
  35. func reload() {
  36. taskCfgList = db.MapCrontabCfg(db.Db)
  37. if len(*taskCfgList) > 0 {
  38. // 删除原有所有任务
  39. if len(entryIds) > 0 {
  40. for _, v := range entryIds {
  41. if v != baseEntryId {
  42. timer.Remove(v)
  43. }
  44. }
  45. entryIds = nil
  46. }
  47. var (
  48. entryId cron.EntryID
  49. err error
  50. )
  51. // 添加任务
  52. for _, v := range *taskCfgList {
  53. if _, ok := jobs[v.Key]; ok && v.Val != "" {
  54. fmt.Println(v.Val)
  55. if entryId, err = timer.AddFunc(v.Val, doTask(v.Key)); err == nil {
  56. entryIds = append(entryIds, entryId)
  57. }
  58. }
  59. }
  60. }
  61. }
  62. func doTask(fnName string) func() {
  63. return func() {
  64. begin := time.Now().Local()
  65. jobs[fnName](db.Db)
  66. end := time.Now().Local()
  67. logx.Infof(
  68. "[%s] AutoTask <%s> started at <%s>, ended at <%s> duration <%s>",
  69. fnName,
  70. begin.Format("2006-01-02 15:04:05.000"),
  71. end.Format("2006-01-02 15:04:05.000"),
  72. time.Duration(end.UnixNano()-begin.UnixNano()).String(),
  73. )
  74. }
  75. }
  76. // 增加自动任务队列
  77. func initTasks() {
  78. jobs[taskMd.SyncCentralKitchenForSchoolPackageOrdState] = taskSyncCentralKitchenForSchoolPackageOrdState
  79. jobs[taskMd.SyncCentralKitchenForSchoolUserWithDayState] = taskSyncCentralKitchenForSchoolUserWithDayState
  80. }