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

92 lines
1.9 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. func reload() {
  38. taskCfgList = db.MapCrontabCfg(db.Db)
  39. if len(*taskCfgList) > 0 {
  40. // 删除原有所有任务
  41. if len(entryIds) > 0 {
  42. for _, v := range entryIds {
  43. if v != baseEntryId {
  44. timer.Remove(v)
  45. }
  46. }
  47. entryIds = nil
  48. }
  49. var (
  50. entryId cron.EntryID
  51. err error
  52. )
  53. // 添加任务
  54. for _, v := range *taskCfgList {
  55. if _, ok := jobs[v.K]; ok && v.V != "" {
  56. fmt.Println(v.V)
  57. if entryId, err = timer.AddFunc(v.V, doTask(v.K)); err == nil {
  58. entryIds = append(entryIds, entryId)
  59. }
  60. }
  61. }
  62. }
  63. }
  64. func doTask(fnName string) func() {
  65. return func() {
  66. begin := time.Now().Local()
  67. jobs[fnName](db.Db)
  68. end := time.Now().Local()
  69. logx.Infof(
  70. "[%s] AutoTask <%s> started at <%s>, ended at <%s> duration <%s>",
  71. fnName,
  72. begin.Format("2006-01-02 15:04:05.000"),
  73. end.Format("2006-01-02 15:04:05.000"),
  74. time.Duration(end.UnixNano()-begin.UnixNano()).String(),
  75. )
  76. }
  77. }
  78. // 增加自动任务队列
  79. func initTasks() {
  80. jobs[taskMd.CronCalcMasterDataStatistics] = taskCalcMasterDataStatistics // 计算站长数据统计
  81. }