Skip to content

Instantly share code, notes, and snippets.

@mytholog
Forked from egorlepa/batcher goroutine
Created April 17, 2025 11:56
Show Gist options
  • Save mytholog/41e39b8cba0c5974eeb4d63ccc289f98 to your computer and use it in GitHub Desktop.
Save mytholog/41e39b8cba0c5974eeb4d63ccc289f98 to your computer and use it in GitHub Desktop.
func batcher[T any](in chan T, out chan []T, batchSize int, timeout time.Duration) {
for {
batch := make([]T, 0, batchSize)
t := time.After(timeout)
for batchReady := false; !batchReady; {
select {
case e := <-in:
batch = append(batch, e)
if len(batch) == batchSize {
batchReady = true
}
case <-t:
if len(batch) > 0 {
batchReady = true
break
}
t = time.After(timeout)
}
if batchReady == true {
out <- batch
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment