getNewActiveUser.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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, ed time.Time) []*NewActiveMsg {
  15. var (
  16. mgoIds []string
  17. ctx = context.Background()
  18. )
  19. stYear, stMonth, stDay := st.Date()
  20. _, edMonth, edDay := ed.Date()
  21. nst := st.AddDate(0, -1, 0)
  22. _, nstMonth, nstDay := nst.Date()
  23. //昨天所有活跃用户
  24. res, err := g.DB("useranaly").Query(ctx, fmt.Sprintf(`SELECT DISTINCT user_mongoid FROM user_countbyhour
  25. WHERE CONCAT(month, '-', day) >= '%s' AND CONCAT(month, '-', day) <= '%s'`, fmt.Sprintf("%d-%d", int(stMonth), stDay), fmt.Sprintf("%d-%d", int(edMonth), edDay)))
  26. //res, err := g.DB().Query(ctx, fmt.Sprintf(`SELECT DISTINCT user_mongoid FROM user_countbyhour WHERE %s `, sql))
  27. if err == nil && !res.IsEmpty() {
  28. for _, m := range res.List() {
  29. mongoid := gconv.String(m["user_mongoid"])
  30. mgoIds = append(mgoIds, mongoid)
  31. }
  32. }
  33. var (
  34. lock sync.Mutex
  35. data []*NewActiveMsg
  36. )
  37. pool := make(chan bool, 5)
  38. wait := &sync.WaitGroup{}
  39. for _, id := range mgoIds {
  40. pool <- true
  41. wait.Add(1)
  42. go func(mId string) {
  43. defer func() {
  44. wait.Done()
  45. <-pool
  46. }()
  47. count, _ := g.DB("useranaly").GetCount(ctx, fmt.Sprintf(`SELECT count(1) FROM user_countbyhour
  48. 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)))
  49. if count == 0 { //统计昨天之前30天不活跃用户
  50. lock.Lock()
  51. data = append(data, &NewActiveMsg{
  52. MgoUserID: mId,
  53. TimeStamp: time.Date(stYear, stMonth, stDay, 0, 0, 0, 0, time.Local).Unix(),
  54. })
  55. lock.Unlock()
  56. }
  57. }(id)
  58. }
  59. wait.Wait()
  60. return data
  61. }