Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The routine you use to read from the message channel should define a cache in which incoming messages are stored. These cached messages are then sent to the remote server in bulk either when the cache reaches 100 messages, or 5 seconds have passed. You use a timer channel and Go's <code>select</code> statement to determine which one occurs first.</p> <p>The following example can be run on the <a href="http://play.golang.org/p/KjWz95tsE0">Go playground</a></p> <pre><code>package main import ( "fmt" "math/rand" "time" ) type Message int const ( CacheLimit = 100 CacheTimeout = 5 * time.Second ) func main() { input := make(chan Message, CacheLimit) go poll(input) generate(input) } // poll checks for incoming messages and caches them internally // until either a maximum amount is reached, or a timeout occurs. func poll(input &lt;-chan Message) { cache := make([]Message, 0, CacheLimit) tick := time.NewTicker(CacheTimeout) for { select { // Check if a new messages is available. // If so, store it and check if the cache // has exceeded its size limit. case m := &lt;-input: cache = append(cache, m) if len(cache) &lt; CacheLimit { break } // Reset the timeout ticker. // Otherwise we will get too many sends. tick.Stop() // Send the cached messages and reset the cache. send(cache) cache = cache[:0] // Recreate the ticker, so the timeout trigger // remains consistent. tick = time.NewTicker(CacheTimeout) // If the timeout is reached, send the // current message cache, regardless of // its size. case &lt;-tick.C: send(cache) cache = cache[:0] } } } // send sends cached messages to a remote server. func send(cache []Message) { if len(cache) == 0 { return // Nothing to do here. } fmt.Printf("%d message(s) pending\n", len(cache)) } // generate creates some random messages and pushes them into the given channel. // // Not part of the solution. This just simulates whatever you use to create // the messages by creating a new message at random time intervals. func generate(input chan&lt;- Message) { for { select { case &lt;-time.After(time.Duration(rand.Intn(100)) * time.Millisecond): input &lt;- Message(rand.Int()) } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload