github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/timer/tick-limit.go (about)

     1  /* For license and copyright information please see the LEGAL file in the code repository */
     2  
     3  package timer
     4  
     5  import (
     6  	"github.com/GeniusesGroup/libgo/protocol"
     7  )
     8  
     9  func NewLimitTicker(first, interval protocol.Duration, periodNumber int64) (t *LimitTicker, err protocol.Error) {
    10  	if periodNumber < 1 {
    11  		panic("timer - LimitTicker: periodNumber must be more than one.")
    12  	}
    13  
    14  	var timer LimitTicker
    15  	timer.Init()
    16  	timer.periodNumber = periodNumber
    17  	err = timer.Tick(first, interval)
    18  	t = &timer
    19  	return
    20  }
    21  
    22  type LimitTicker struct {
    23  	periodNumber int64 // -1 means no limit
    24  	Sync
    25  }
    26  
    27  //libgo:impl protocol.Timer
    28  func (t *LimitTicker) Init() {
    29  	// Give the channel a 1-element buffer.
    30  	// If the client falls behind while reading, we drop ticks
    31  	// on the floor until the client catches up.
    32  	t.signal = make(chan struct{}, 1)
    33  	t.Async.Init(t)
    34  }
    35  
    36  func (t *LimitTicker) RemainingNumber() int64 { return t.periodNumber }
    37  
    38  // TimerHandler or NotifyChannel does a non-blocking send the signal on t.signal
    39  func (t *LimitTicker) TimerHandler() {
    40  	select {
    41  	case t.signal <- struct{}{}:
    42  	default:
    43  	}
    44  
    45  	if t.periodNumber > 0 {
    46  		t.periodNumber--
    47  	} else {
    48  		t.Stop()
    49  	}
    50  }