delete.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package service
  2. import (
  3. "context"
  4. "time"
  5. "go-common/library/log"
  6. "go-common/library/stat/prom"
  7. )
  8. const _businessArchive = 3
  9. const _delLen = 1000
  10. func (s *Service) shouldDelete() bool {
  11. now := time.Now()
  12. return now.Hour() >= s.c.Job.DeleteStartHour && now.Hour() < s.c.Job.DeleteEndHour
  13. }
  14. func (s *Service) deleteproc() {
  15. for {
  16. now := time.Now()
  17. if !s.shouldDelete() {
  18. time.Sleep(time.Minute)
  19. continue
  20. }
  21. if ok, err := s.dao.DelLock(context.Background()); err != nil {
  22. time.Sleep(time.Second)
  23. continue
  24. } else if !ok {
  25. log.Info("not get lock wait.")
  26. time.Sleep(time.Hour * 6)
  27. continue
  28. }
  29. log.Info("start clean db")
  30. bs, err := s.dao.Businesses(context.Background())
  31. if err != nil {
  32. time.Sleep(time.Second)
  33. continue
  34. }
  35. for _, b := range bs {
  36. if b.TTL <= 0 {
  37. continue
  38. }
  39. endTime := time.Unix(now.Unix()-b.TTL, 0)
  40. startTime, err := s.dao.EarlyHistory(context.Background(), b.ID)
  41. if err != nil {
  42. continue
  43. }
  44. log.Info("start clean business %s start:%v end: %v", b.Name, startTime, endTime)
  45. var count int64
  46. for startTime.Before(endTime) {
  47. if !s.shouldDelete() {
  48. log.Info("%s not delete time.", b.Name)
  49. break
  50. }
  51. partTime := startTime.Add(time.Duration(s.c.Job.DeleteStep))
  52. rows, err := s.dao.DeleteHistories(context.Background(), b.ID, startTime, partTime)
  53. prom.BusinessInfoCount.Add("del-"+b.Name, rows)
  54. if err != nil {
  55. time.Sleep(time.Second)
  56. continue
  57. }
  58. count += rows
  59. // 删除完这个时间段的数据后再删除下个时间段
  60. if rows == 0 {
  61. startTime = partTime
  62. }
  63. }
  64. log.Info("end clean business %s, rows: %v", b.Name, count)
  65. }
  66. log.Info("end clean db")
  67. time.Sleep(time.Hour * 6)
  68. }
  69. }