Skip to content

Instantly share code, notes, and snippets.

@deefdragon
Last active December 1, 2020 18:53
Show Gist options
  • Save deefdragon/fa3de853f7bffdc7410eee200bf41f35 to your computer and use it in GitHub Desktop.
Save deefdragon/fa3de853f7bffdc7410eee200bf41f35 to your computer and use it in GitHub Desktop.
golang x/time/rate example
package main
import (
"fmt"
"sync"
"time"
"golang.org/x/time/rate"
)
func main() {
// 800 requests per minute.
l := rate.NewLimiter(rate.Every(time.Second/13), 1)
wg := &sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(1)
go run(l, wg, i)
}
wg.Wait()
fmt.Printf("Completed the requests\n")
}
func run(l *rate.Limiter, wg *sync.WaitGroup, i int) {
r := l.Reserve()
wait := r.Delay()
if wait > time.Second*3 {
fmt.Printf("%d: Wait Too Long For Request %s\n", i, wait.String())
} else {
time.Sleep(wait)
fmt.Printf("%d: Waited For Request. %s\n", i, wait.String())
}
wg.Done()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment