retry.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package offer
  2. import (
  3. "context"
  4. "encoding/json"
  5. "time"
  6. "go-common/app/job/main/app-wall/model/offer"
  7. "go-common/library/log"
  8. )
  9. const (
  10. _upActiveRetry = 5
  11. _sleep = 100 * time.Millisecond
  12. )
  13. func (s *Service) retryproc() {
  14. defer s.waiter.Done()
  15. var (
  16. bs []byte
  17. err error
  18. )
  19. c := context.TODO()
  20. msg := &offer.Retry{}
  21. for {
  22. if s.closed {
  23. break
  24. }
  25. if bs, err = s.dao.PopFail(c); err != nil {
  26. time.Sleep(5 * time.Second)
  27. continue
  28. }
  29. if len(bs) == 0 {
  30. time.Sleep(5 * time.Second)
  31. continue
  32. }
  33. if err = json.Unmarshal(bs, msg); err != nil {
  34. log.Error("json.Unmarshal(%s) error(%v)", bs, err)
  35. continue
  36. }
  37. log.Info("retry action(%s) data(%s)", msg.Action, bs)
  38. switch msg.Action {
  39. case offer.ActionActive:
  40. if msg.Data != nil {
  41. if err = retry(func() (err error) {
  42. return s.dao.Active(c, msg.Data.OS, msg.Data.IMEI, msg.Data.Androidid, msg.Data.Mac, "")
  43. }, _upActiveRetry, _sleep); err != nil {
  44. log.Error("%+v", err)
  45. if err = s.syncRetry(c, offer.ActionActive, msg.Data.OS, msg.Data.IMEI, msg.Data.Androidid, msg.Data.Mac); err != nil {
  46. log.Error("%+v", err)
  47. }
  48. return
  49. }
  50. }
  51. }
  52. }
  53. }
  54. func retry(callback func() error, retry int, sleep time.Duration) (err error) {
  55. for i := 0; i < retry; i++ {
  56. if err = callback(); err == nil {
  57. return
  58. }
  59. time.Sleep(sleep)
  60. }
  61. return
  62. }
  63. func (s *Service) syncRetry(c context.Context, action, os, imei, androidid, mac string) (err error) {
  64. retry := &offer.Retry{Action: action, Data: &offer.Data{OS: os, IMEI: imei, Androidid: androidid, Mac: mac}}
  65. return s.dao.PushFail(c, retry)
  66. }