广告平台(总站长使用)
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.
 
 
 
 
 
 

105 lines
2.4 KiB

  1. package task
  2. import (
  3. taskMd "applet/app/task/md"
  4. db "code.fnuoos.com/zhimeng/model.git/src"
  5. "code.fnuoos.com/zhimeng/model.git/src/model"
  6. "fmt"
  7. "time"
  8. "github.com/robfig/cron/v3"
  9. "xorm.io/xorm"
  10. "applet/app/utils/logx"
  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.SysCfg
  18. ch = make(chan int, 30)
  19. workerNum = 15 // 智盟跟单并发数量
  20. otherCh = make(chan int, 30)
  21. )
  22. func Init() {
  23. // 初始化任务列表
  24. initTasks()
  25. var err error
  26. timer = cron.New()
  27. // reload为初始化数据库方法
  28. if baseEntryId, err = timer.AddFunc("@every 15m", reload); err != nil {
  29. _ = logx.Fatal(err)
  30. }
  31. }
  32. func Run() {
  33. reload()
  34. timer.Start()
  35. _ = logx.Info("auto tasks running...")
  36. }
  37. // MapCrontabCfg 获取自动任务队列
  38. func MapCrontabCfg(eg *xorm.Engine) *[]model.SysCfg {
  39. var c []model.SysCfg
  40. // 数据库查询如果有下划线会认为是一个任意字符
  41. if err := eg.Where("`k` LIKE 'cron\\_%' AND v != ''").Cols("`k`,`v`").Find(&c); err != nil || len(c) == 0 {
  42. logx.Warn(err)
  43. return nil
  44. }
  45. return &c
  46. }
  47. func reload() {
  48. taskCfgList = MapCrontabCfg(db.Db)
  49. if len(*taskCfgList) > 0 {
  50. // 删除原有所有任务
  51. if len(entryIds) > 0 {
  52. for _, v := range entryIds {
  53. if v != baseEntryId {
  54. timer.Remove(v)
  55. }
  56. }
  57. entryIds = nil
  58. }
  59. var (
  60. entryId cron.EntryID
  61. err error
  62. )
  63. // 添加任务
  64. for _, v := range *taskCfgList {
  65. if _, ok := jobs[v.K]; ok && v.V != "" {
  66. fmt.Println(v.V)
  67. if entryId, err = timer.AddFunc(v.V, doTask(v.K)); err == nil {
  68. entryIds = append(entryIds, entryId)
  69. }
  70. }
  71. }
  72. }
  73. }
  74. func doTask(fnName string) func() {
  75. return func() {
  76. begin := time.Now().Local()
  77. jobs[fnName](db.Db)
  78. end := time.Now().Local()
  79. logx.Infof(
  80. "[%s] AutoTask <%s> started at <%s>, ended at <%s> duration <%s>",
  81. fnName,
  82. begin.Format("2006-01-02 15:04:05.000"),
  83. end.Format("2006-01-02 15:04:05.000"),
  84. time.Duration(end.UnixNano()-begin.UnixNano()).String(),
  85. )
  86. }
  87. }
  88. // 增加自动任务队列
  89. func initTasks() {
  90. jobs[taskMd.CronCalcMasterDataStatistics] = taskCalcMasterDataStatistics // 计算站长数据统计
  91. jobs[taskMd.CronMediumSettlementState] = taskMediumSettlementState // 媒体结算单状态
  92. jobs[taskMd.CronAgentSettlementState] = taskAgentSettlementState // 代理结算单状态
  93. }