Skip to content

Commit

Permalink
feat(scheduler): replace sync/atomic by go.uber.org/atomic
Browse files Browse the repository at this point in the history
  • Loading branch information
fcote committed Feb 24, 2023
1 parent 0f087fb commit 87fe5b5
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions scheduler/pkg/fmp/rate_limit_timer.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
package fmp

import (
"sync/atomic"
"time"

"go.uber.org/atomic"
)

const timerDuration = 1 * time.Minute

// RateLimitTimer is a timer that keeps track of the number of requests
type RateLimitTimer struct {
timer *time.Timer
end time.Time
nRequests atomic.Uint64
end *atomic.Time
nRequests *atomic.Uint64
maxRequestsPerMin uint64
}

// NewRateLimitTimer creates a new RateLimitTimer
func NewRateLimitTimer(maxRequestsPerMin int) *RateLimitTimer {
t := &RateLimitTimer{
end: time.Now().Add(timerDuration),
end: atomic.NewTime(time.Now().Add(timerDuration)),
nRequests: atomic.NewUint64(0),
maxRequestsPerMin: uint64(maxRequestsPerMin),
}
t.timer = time.AfterFunc(timerDuration, t.reset)
Expand All @@ -31,7 +33,7 @@ func (t *RateLimitTimer) Wait() {
t.nRequests.Add(1)

if t.nRequests.Load() >= t.maxRequestsPerMin {
timeToWait := time.Until(t.end)
timeToWait := time.Until(t.end.Load())
<-time.After(timeToWait)
}
}
Expand All @@ -41,5 +43,5 @@ func (t *RateLimitTimer) reset() {
t.nRequests.Store(0)

t.timer.Reset(timerDuration)
t.end = time.Now().Add(timerDuration)
t.end.Store(time.Now().Add(timerDuration))
}

0 comments on commit 87fe5b5

Please sign in to comment.