:
, , , sendRegularHeartbeats(), case <-ctx.Done() , , , . case <-time.After(1 * time.Second) 1 , . , , .
case switch ( - , ), - , case select.
Spec: :
, , , . , , . , "select" , .
, . .
, (). select (, ), select, default, , . 2 select, <-ctx.Done(), , .
time.Ticker time.After() (time.After() time.Ticker , , "" ).
:
func sendRegularHeartbeats(ctx context.Context) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
default:
}
select {
case <-ctx.Done():
return
case <-ticker.C:
sendHeartbeat()
}
}
}
, sendRegularHeartbeats(), / Go Playground.
cancel() 2,5 , 2 :
ctx, cancel := context.WithCancel(context.Background())
go sendRegularHeartbeats(ctx)
time.Sleep(time.Millisecond * 2500)
cancel()
time.Sleep(time.Second * 2)
Go Playground.