智慧食堂
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

92 righe
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. initTasks()
  24. var err error
  25. timer = cron.New()
  26. // reload为初始化数据库方法
  27. if baseEntryId, err = timer.AddFunc("@every 30m", reload); err != nil {
  28. _ = logx.Fatal(err)
  29. }
  30. }
  31. func Run() {
  32. reload()
  33. timer.Start()
  34. _ = logx.Info("auto tasks running...")
  35. }
  36. func reload() {
  37. taskCfgList = db.MapCrontabCfg(db.Db)
  38. if len(*taskCfgList) > 0 {
  39. // 删除原有所有任务
  40. if len(entryIds) > 0 {
  41. for _, v := range entryIds {
  42. if v != baseEntryId {
  43. timer.Remove(v)
  44. }
  45. }
  46. entryIds = nil
  47. }
  48. var (
  49. entryId cron.EntryID
  50. err error
  51. )
  52. // 添加任务
  53. for _, v := range *taskCfgList {
  54. if _, ok := jobs[v.Key]; ok && v.Val != "" {
  55. fmt.Println(v.Val)
  56. if entryId, err = timer.AddFunc(v.Val, doTask(v.Key)); err == nil {
  57. entryIds = append(entryIds, entryId)
  58. }
  59. }
  60. }
  61. }
  62. }
  63. func doTask(fnName string) func() {
  64. return func() {
  65. begin := time.Now().Local()
  66. jobs[fnName](db.Db)
  67. end := time.Now().Local()
  68. logx.Infof(
  69. "[%s] AutoTask <%s> started at <%s>, ended at <%s> duration <%s>",
  70. fnName,
  71. begin.Format("2006-01-02 15:04:05.000"),
  72. end.Format("2006-01-02 15:04:05.000"),
  73. time.Duration(end.UnixNano()-begin.UnixNano()).String(),
  74. )
  75. }
  76. }
  77. // 增加自动任务队列
  78. func initTasks() {
  79. jobs[taskMd.SyncCentralKitchenForSchoolPackageOrdState] = taskSyncCentralKitchenForSchoolPackageOrdState
  80. //jobs[taskMd.SyncCentralKitchenForSchoolUserWithDayState] = taskSyncCentralKitchenForSchoolUserWithDayState
  81. }