timerangegen.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package main
  2. import (
  3. "context"
  4. log "github.com/sirupsen/logrus"
  5. "time"
  6. )
  7. type TimeRange struct {
  8. begin time.Time
  9. end time.Time
  10. }
  11. func (tr TimeRange) SimpleString() string {
  12. return "[" + tr.begin.Format("15:04:05") + "-" + tr.end.Format("15:04:05") + ")"
  13. }
  14. type TimeRangeGen struct {
  15. lastGenTimeUpper time.Time
  16. upperTimeDurationFromNow time.Duration
  17. timeRangeChannel chan TimeRange
  18. minRangeDuration time.Duration
  19. maxRangeDuration time.Duration
  20. cancel context.CancelFunc
  21. logger *log.Entry
  22. }
  23. func NewTimeRangeGen(upperTimeDurationFromNow time.Duration, trRangeCh chan TimeRange, lastGenTimeUpper time.Time, minRangeDuration time.Duration,
  24. maxRangeDuration time.Duration) *TimeRangeGen {
  25. logger := log.WithFields(log.Fields{"loggerName": "TimeRangeGen"})
  26. return &TimeRangeGen{
  27. upperTimeDurationFromNow: upperTimeDurationFromNow,
  28. lastGenTimeUpper: lastGenTimeUpper,
  29. minRangeDuration: minRangeDuration,
  30. maxRangeDuration: maxRangeDuration,
  31. logger: logger,
  32. timeRangeChannel: trRangeCh,
  33. }
  34. }
  35. func (tr *TimeRangeGen) start(parentContext context.Context) {
  36. ctx, cancel := context.WithCancel(parentContext)
  37. tr.cancel = cancel
  38. go tr.startGen(ctx)
  39. tr.logger.Infof("started")
  40. }
  41. func (tr *TimeRangeGen) startGen(ctx context.Context) {
  42. tm := time.NewTicker(1 * time.Second)
  43. forLoop:
  44. for {
  45. select {
  46. case <-ctx.Done():
  47. tr.logger.Infof("stop signal received, quit")
  48. break forLoop
  49. case <-tm.C:
  50. tr.checkGenTimeRange()
  51. }
  52. }
  53. }
  54. func (tr *TimeRangeGen) stop() {
  55. tr.logger.Infof("stopping")
  56. tr.cancel()
  57. tr.logger.Infof("stoped")
  58. }
  59. func (tr *TimeRangeGen) checkGenTimeRange() {
  60. now := time.Now()
  61. upper := now.Add(-tr.upperTimeDurationFromNow)
  62. range2Gen := upper.Sub(tr.lastGenTimeUpper)
  63. if range2Gen < tr.minRangeDuration {
  64. tr.logger.Debugf("%v < %v, skip gen", range2Gen, tr.minRangeDuration)
  65. return
  66. }
  67. tr.logger.Debugf("start check gen time range in [%v, %v)", tr.lastGenTimeUpper, upper)
  68. for i := tr.lastGenTimeUpper; i.Before(upper); i = i.Add(tr.maxRangeDuration) {
  69. end := i.Add(tr.minRangeDuration)
  70. if end.After(upper) {
  71. end = upper
  72. }
  73. tr.timeRangeChannel <- TimeRange{begin: i, end: end}
  74. tr.lastGenTimeUpper = end
  75. }
  76. }