alive waits for subtasks, coordinate graceful or fast shutdown. sync.WaitGroup on steroids.
Key takeaways:
go get github.com/temoto/alive/v2
- Zero value of
alive.Alive{}
is not usable ever, you must useNewAlive()
constructor.
srv := MyServer{ alive: alive.NewAlive() }
- Call
.Add(n)
and.Done()
just as withWaitGroup
but check return value.
for {
task := <-queue
if !srv.alive.Add(1) {
break
}
go func() {
// be useful
srv.alive.Done()
}()
}
- Call
.Stop()
to switchIsRunning
and stop creating new tasks if programmed so.
sigShutdownChan := make(chan os.Signal, 1)
signal.Notify(sigShutdownChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func(ch <-chan os.Signal) {
<-ch
log.Printf("graceful stop")
sdnotify("READY=0\nSTATUS=stopping\n")
srv.alive.Stop()
}(sigShutdownChan)
- Call
.Wait()
to synchronize on all subtasks.Done()
, just as withWaitGroup
.
func main() {
// ...
srv.alive.Wait()
}
.StopChan()
lets you observe.Stop()
call from another place. A better option toIsRunning()
poll.
stopch := srv.alive.StopChan()
for {
select {
case job := <-queue:
// be useful
case <-stopch:
// break for loop
}
}
.WaitChan()
isselect
-friendly version of.Wait()
.- There are few
panic()
which should never happen, like debug-build assertions. But please tell me if you find a way to trigger"Bug in package"