stopper := util.NewStopper() defer stopper.Stop() for { // do some work here select { case <-time.After(time.Second): if stopper.ShouldStop() { return } } }
func (s *server) Start() error { s.stopper = util.NewStopper() s.stopper.RunWorker(func() { <-s.stopper.ShouldQuiesce() s.grpc.Stop() }) // start some other services here return nil } func (s *server) Stop() { s.stopper.Stop() }In this example, the Stopper type is used to gracefully stop a gRPC server. We create a new stopper and use its RunWorker method to start a goroutine that waits for the ShouldQuiesce method to return. When ShouldQuiesce returns, the gRPC server is stopped. The Stop method is called externally to stop the server.