github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2013/go1.1/timer.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"math/rand"
     8  	"time"
     9  )
    10  
    11  func init() {
    12  	rand.Seed(10)
    13  }
    14  
    15  func sendMessages() chan string {
    16  	ch := make(chan string)
    17  	go func() {
    18  		for i := 0; ; i++ {
    19  			time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
    20  			ch <- fmt.Sprintf("message %v", i)
    21  		}
    22  	}()
    23  	return ch
    24  }
    25  
    26  func main() {
    27  	timeout := time.NewTimer(80 * time.Millisecond)
    28  	ch := sendMessages()
    29  	for {
    30  		select {
    31  		case msg := <-ch:
    32  			fmt.Println(msg)
    33  			timeout.Reset(80 * time.Millisecond)
    34  		case <-timeout.C:
    35  			fmt.Println("timeout")
    36  			return
    37  		}
    38  	}
    39  }