蛋蛋星球-客户端
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.
 
 
 
 
 
 

94 rader
2.0 KiB

  1. package task
  2. import (
  3. "applet/app/db"
  4. taskMd "applet/app/task/md"
  5. "code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
  6. "code.fnuoos.com/EggPlanet/egg_models.git/src/model"
  7. "fmt"
  8. "time"
  9. "applet/app/utils/logx"
  10. "github.com/robfig/cron/v3"
  11. "xorm.io/xorm"
  12. )
  13. var (
  14. timer *cron.Cron
  15. jobs = map[string]func(*xorm.Engine){}
  16. baseEntryId cron.EntryID
  17. entryIds []cron.EntryID
  18. taskCfgList *[]model.CronTask
  19. ch = make(chan int, 30)
  20. workerNum = 15 // 并发数量
  21. )
  22. func Init() {
  23. // 初始化任务列表
  24. initTasks()
  25. var err error
  26. timer = cron.New()
  27. // reload为初始化数据库方法
  28. if baseEntryId, err = timer.AddFunc("@every 30m", 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. cronTaskDb := implement.NewCronTaskDb(db.Db)
  39. taskCfgList = cronTaskDb.MapCrontabCfg()
  40. if len(*taskCfgList) > 0 {
  41. // 删除原有所有任务
  42. if len(entryIds) > 0 {
  43. for _, v := range entryIds {
  44. if v != baseEntryId {
  45. timer.Remove(v)
  46. }
  47. }
  48. entryIds = nil
  49. }
  50. var (
  51. entryId cron.EntryID
  52. err error
  53. )
  54. // 添加任务
  55. for _, v := range *taskCfgList {
  56. if _, ok := jobs[v.Key]; ok && v.Val != "" {
  57. fmt.Println(v.Val)
  58. if entryId, err = timer.AddFunc(v.Val, doTask(v.Key)); err == nil {
  59. entryIds = append(entryIds, entryId)
  60. }
  61. }
  62. }
  63. }
  64. }
  65. func doTask(fnName string) func() {
  66. return func() {
  67. begin := time.Now().Local()
  68. jobs[fnName](db.Db)
  69. end := time.Now().Local()
  70. logx.Infof(
  71. "[%s] AutoTask <%s> started at <%s>, ended at <%s> duration <%s>",
  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.CronEggEnergyAutoRecordPrices] = taskEggEnergyAutoRecordPrices
  82. jobs[taskMd.CronEggEnergyDealPlatformRevenueData] = taskEggEnergyDealPlatformRevenueData
  83. jobs[taskMd.CronEggEnergyDealFundData] = taskEggEnergyDealFundData
  84. }