Skip to content

Instantly share code, notes, and snippets.

@ivan3bx
Last active September 15, 2017 05:34
Show Gist options
  • Save ivan3bx/bb4ee0ee961dfdda0877b63445dc3ff0 to your computer and use it in GitHub Desktop.
Save ivan3bx/bb4ee0ee961dfdda0877b63445dc3ff0 to your computer and use it in GitHub Desktop.
simple throttling of work in go
package main
import (
"fmt"
"time"
)
func main() {
// queue of size 10
queue := make(chan string, 10)
// generate some data over time
go func() {
time.Sleep(time.Second * 3)
for i := 0; i < 4; i++ {
queue<- fmt.Sprintf("Item #%d", i)
}
time.Sleep(time.Second * 7)
for i := 0; i < 10; i++ {
queue<- fmt.Sprintf("Item #%d", i)
}
}()
throttle := time.Tick(time.Second)
for {
fmt.Println("Tick")
<-throttle // rate limit
fmt.Println("Work! ", <-queue, time.Now())
// channel selector will reset the throttle to prevent if firing twice in a row
select {
case <-throttle:
default:
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment