github.com/ngicks/gokugen@v0.0.5/common/timer.go (about)

     1  package common
     2  
     3  //go:generate mockgen -source timer.go -destination __mock/timer.go
     4  
     5  import "time"
     6  
     7  // ITimer is timer interface.
     8  // Intention is to use as an unexported field of some structs.
     9  // And make it mock-able inside internal tests.
    10  type ITimer interface {
    11  	GetChan() <-chan time.Time
    12  	Reset(to, now time.Time)
    13  	Stop()
    14  }
    15  
    16  // TimerImpl is a struct that implements ITimer.
    17  type TimerImpl struct {
    18  	*time.Timer
    19  }
    20  
    21  // NewTimerImpl returns newly created TimerImpl.
    22  // Timer is stopped after return.
    23  func NewTimerImpl() *TimerImpl {
    24  	timer := time.NewTimer(time.Second)
    25  	if !timer.Stop() {
    26  		<-timer.C
    27  	}
    28  	return &TimerImpl{timer}
    29  }
    30  
    31  func (t *TimerImpl) GetChan() <-chan time.Time {
    32  	return t.C
    33  }
    34  
    35  func (t *TimerImpl) Stop() {
    36  	if !t.Timer.Stop() {
    37  		// non-blocking receive.
    38  		// in case of racy concurrent receivers.
    39  		select {
    40  		case <-t.C:
    41  		default:
    42  		}
    43  	}
    44  }
    45  
    46  func (t *TimerImpl) Reset(to, now time.Time) {
    47  	t.Stop()
    48  	t.Timer.Reset(to.Sub(now))
    49  }