Last active
September 15, 2017 05:34
-
-
Save ivan3bx/bb4ee0ee961dfdda0877b63445dc3ff0 to your computer and use it in GitHub Desktop.
simple throttling of work in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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