// go get golang.org/x/time/rate
package main
import (
"context"
"fmt"
"time"
"golang.org/x/time/rate"
)
func main() {
// 5 events per second, burst up to 10
limiter := rate.NewLimiter(5, 10)
ctx := context.Background()
for i := 0; i < 30; i++ {
// Block until a token is available (or context cancels)
if err := limiter.Wait(ctx); err != nil {
fmt.Println("wait failed:", err); return
}
fmt.Printf("%2d: %s\n", i, time.Now().Format("15:04:05.000"))
}
// Non-blocking — Allow() returns false if a token isn't available
if limiter.Allow() {
// process
}
}
Create a free account and build your private vault. Share publicly whenever you want.