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

     1  // +build ignore,OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"time"
     8  )
     9  
    10  // START OMIT
    11  type Server struct{ quit chan bool }
    12  
    13  func NewServer() *Server {
    14  	s := &Server{make(chan bool)}
    15  	go s.run()
    16  	return s
    17  }
    18  
    19  func (s *Server) run() {
    20  	for {
    21  		select {
    22  		case <-s.quit:
    23  			fmt.Println("finishing task")
    24  			time.Sleep(time.Second)
    25  			fmt.Println("task done")
    26  			s.quit <- true
    27  			return
    28  		case <-time.After(time.Second):
    29  			fmt.Println("running task")
    30  		}
    31  	}
    32  }
    33  
    34  // STOP OMIT
    35  func (s *Server) Stop() {
    36  	fmt.Println("server stopping")
    37  	s.quit <- true
    38  	<-s.quit
    39  	fmt.Println("server stopped")
    40  }
    41  
    42  func main() {
    43  	s := NewServer()
    44  	time.Sleep(2 * time.Second)
    45  	s.Stop()
    46  }