getNewActiveUser.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package public
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/util/gconv"
  7. "sync"
  8. "time"
  9. )
  10. type NewActiveMsg struct {
  11. MgoUserID string
  12. TimeStamp int64 //活跃时间
  13. }
  14. func GetNewActiveUser(st time.Time) ([]*NewActiveMsg, time.Time) {
  15. var (
  16. mgoIds []string
  17. ctx = context.Background()
  18. )
  19. //统计昨天的所有注册用户 过滤掉
  20. end := st.AddDate(0, 0, 1)
  21. ed := time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, st.Location())
  22. stYear, stMonth, stDay := st.Date()
  23. nst := st.AddDate(0, -1, 0)
  24. _, nstMonth, nstDay := nst.Date()
  25. //昨天所有活跃用户
  26. res, err := g.DB("useranaly").Query(ctx, fmt.Sprintf(`SELECT DISTINCT user_mongoid FROM user_countbyhour
  27. WHERE CONCAT(month, '-', day) = '%s'`, fmt.Sprintf("%d-%d", int(stMonth), stDay)))
  28. //res, err := g.DB().Query(ctx, fmt.Sprintf(`SELECT DISTINCT user_mongoid FROM user_countbyhour WHERE %s `, sql))
  29. if err == nil && !res.IsEmpty() {
  30. for _, m := range res.List() {
  31. mongoid := gconv.String(m["user_mongoid"])
  32. mgoIds = append(mgoIds, mongoid)
  33. }
  34. }
  35. var (
  36. lock sync.Mutex
  37. data []*NewActiveMsg
  38. )
  39. pool := make(chan bool, 5)
  40. wait := &sync.WaitGroup{}
  41. for _, id := range mgoIds {
  42. pool <- true
  43. wait.Add(1)
  44. go func(mId string) {
  45. defer func() {
  46. wait.Done()
  47. <-pool
  48. }()
  49. count, _ := g.DB("useranaly").GetCount(ctx, fmt.Sprintf(`SELECT count(1) FROM user_countbyhour
  50. WHERE user_mongoid = '%s' and CONCAT(month, '-', day) >= '%s' AND CONCAT(month, '-', day) < '%s';`, mId, fmt.Sprintf("%d-%d", int(nstMonth), nstDay), fmt.Sprintf("%d-%d", int(stMonth), stDay)))
  51. if count == 0 { //统计昨天之前30天不活跃用户
  52. lock.Lock()
  53. data = append(data, &NewActiveMsg{
  54. MgoUserID: mId,
  55. TimeStamp: time.Date(stYear, stMonth, stDay, 0, 0, 0, 0, time.Local).Unix(),
  56. })
  57. lock.Unlock()
  58. }
  59. }(id)
  60. }
  61. wait.Wait()
  62. return data, ed
  63. }