一物一码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

init.go 1.9 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package task
  2. import (
  3. taskMd "applet/app/task/md"
  4. "time"
  5. "applet/app/db/model"
  6. "applet/app/utils/logx"
  7. "github.com/robfig/cron/v3"
  8. "xorm.io/xorm"
  9. )
  10. var (
  11. timer *cron.Cron
  12. jobs = map[string]func(*xorm.Engine, string){}
  13. baseEntryId cron.EntryID
  14. entryIds []cron.EntryID
  15. taskCfgList map[string]*[]model.SysCfg
  16. ch = make(chan int, 30)
  17. workerNum = 15 // 智盟跟单并发数量
  18. otherCh = make(chan int, 30)
  19. otherWorkerNum = 18 // 淘宝, 苏宁, 考拉并发量
  20. )
  21. func Init() {
  22. // 初始化任务列表
  23. initTasks()
  24. var err error
  25. timer = cron.New()
  26. // reload为初始化数据库方法
  27. if baseEntryId, err = timer.AddFunc("@every 15m", 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. // 重新初始化数据库
  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 dbName, v := range taskCfgList {
  54. for _, vv := range *v {
  55. if _, ok := jobs[vv.Key]; ok && vv.Val != "" {
  56. // fmt.Println(vv.Val)
  57. if entryId, err = timer.AddFunc(vv.Val, doTask(dbName, vv.Key)); err == nil {
  58. entryIds = append(entryIds, entryId)
  59. }
  60. }
  61. }
  62. }
  63. }
  64. }
  65. func doTask(dbName, fnName string) func() {
  66. return func() {
  67. begin := time.Now().Local()
  68. end := time.Now().Local()
  69. logx.Infof(
  70. "[%s] AutoTask <%s> started at <%s>, ended at <%s> duration <%s>",
  71. dbName,
  72. fnName,
  73. begin.Format("2006-01-02 15:04:05.000"),
  74. end.Format("2006-01-02 15:04:05.000"),
  75. time.Duration(end.UnixNano()-begin.UnixNano()).String(),
  76. )
  77. }
  78. }
  79. // 增加自动任务队列
  80. func initTasks() {
  81. jobs[taskMd.MallCronOrderCancel] = taskCancelOrder // 取消订单
  82. }