12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package main
- import (
- "context"
- log "github.com/sirupsen/logrus"
- "time"
- )
- type TimeRange struct {
- begin time.Time
- end time.Time
- }
- func (tr TimeRange) SimpleString() string {
- return "[" + tr.begin.Format("15:04:05") + "-" + tr.end.Format("15:04:05") + ")"
- }
- type TimeRangeGen struct {
- lastGenTimeUpper time.Time
- upperTimeDurationFromNow time.Duration
- timeRangeChannel chan TimeRange
- minRangeDuration time.Duration
- maxRangeDuration time.Duration
- cancel context.CancelFunc
- logger *log.Entry
- }
- func NewTimeRangeGen(upperTimeDurationFromNow time.Duration, trRangeCh chan TimeRange, lastGenTimeUpper time.Time, minRangeDuration time.Duration,
- maxRangeDuration time.Duration) *TimeRangeGen {
- logger := log.WithFields(log.Fields{"loggerName": "TimeRangeGen"})
- return &TimeRangeGen{
- upperTimeDurationFromNow: upperTimeDurationFromNow,
- lastGenTimeUpper: lastGenTimeUpper,
- minRangeDuration: minRangeDuration,
- maxRangeDuration: maxRangeDuration,
- logger: logger,
- timeRangeChannel: trRangeCh,
- }
- }
- func (tr *TimeRangeGen) start(parentContext context.Context) {
- ctx, cancel := context.WithCancel(parentContext)
- tr.cancel = cancel
- go tr.startGen(ctx)
- tr.logger.Infof("started")
- }
- func (tr *TimeRangeGen) startGen(ctx context.Context) {
- tm := time.NewTicker(1 * time.Second)
- forLoop:
- for {
- select {
- case <-ctx.Done():
- tr.logger.Infof("stop signal received, quit")
- break forLoop
- case <-tm.C:
- tr.checkGenTimeRange()
- }
- }
- }
- func (tr *TimeRangeGen) stop() {
- tr.logger.Infof("stopping")
- tr.cancel()
- tr.logger.Infof("stoped")
- }
- func (tr *TimeRangeGen) checkGenTimeRange() {
- now := time.Now()
- upper := now.Add(-tr.upperTimeDurationFromNow)
- range2Gen := upper.Sub(tr.lastGenTimeUpper)
- if range2Gen < tr.minRangeDuration {
- tr.logger.Debugf("%v < %v, skip gen", range2Gen, tr.minRangeDuration)
- return
- }
- tr.logger.Debugf("start check gen time range in [%v, %v)", tr.lastGenTimeUpper, upper)
- for i := tr.lastGenTimeUpper; i.Before(upper); i = i.Add(tr.maxRangeDuration) {
- end := i.Add(tr.minRangeDuration)
- if end.After(upper) {
- end = upper
- }
- tr.timeRangeChannel <- TimeRange{begin: i, end: end}
- tr.lastGenTimeUpper = end
- }
- }
|