limiter.go 572 B

1234567891011121314151617181920212223242526272829303132
  1. package mathutil
  2. import "time"
  3. //Limiter speed limiter
  4. type Limiter struct {
  5. Rate float64 // 每秒多少个
  6. token chan time.Time
  7. timer *time.Ticker
  8. }
  9. //Token get token
  10. func (l *Limiter) Token() (c <-chan time.Time) {
  11. return l.token
  12. }
  13. func (l *Limiter) putToken() {
  14. for t := range l.timer.C {
  15. l.token <- t
  16. }
  17. }
  18. //NewLimiter create new limiter
  19. func NewLimiter(rate float64) *Limiter {
  20. var l = &Limiter{
  21. Rate: rate,
  22. token: make(chan time.Time, 1),
  23. timer: time.NewTicker(time.Duration(1.0 / rate * float64(time.Second))),
  24. }
  25. go l.putToken()
  26. return l
  27. }