Created
December 30, 2014 17:47
-
-
Save azylman/cc3aded732000c085780 to your computer and use it in GitHub Desktop.
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
// 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