Skip to content

Instantly share code, notes, and snippets.

@azylman
Created December 30, 2014 17:47
Show Gist options
  • Save azylman/cc3aded732000c085780 to your computer and use it in GitHub Desktop.
Save azylman/cc3aded732000c085780 to your computer and use it in GitHub Desktop.
// batchChannel takes in a channel and outputs them grouped into batches. The batch will be sent when
// either there are enough to complete the batchSize or the flushInterval has elapsed.
func batchChannel(in chan interface{}, out chan interface{}, batchSize int, flushInterval time.Duration) {
tickChan := time.Tick(flushInterval)
buffer := make([]interface{}, 0)
for {
select {
case el := <-in:
buffer = append(buffer, el)
if len(buffer) >= batchSize {
out <- buffer
buffer = make([]interface{}, 0)
}
case <-tickChan:
if len(buffer) > 0 {
out <- buffer
buffer = make([]interface{}, 0)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment