golang 的for-select结构,没有default会被阻塞,可以利用定时器任务;
func TimerJob(ctx context.Context) {
ter := time.NewTimer(1 * time.Second)
for {
select {
case <-ctx.Done():
fmt.Println("subctx exit.")
return
case now := <-ter.C:
fmt.Println("++", now)
ter.Reset(1 * time.Second)
}
fmt.Println("--", time.Now())
}
}
func main() {
fmt.Println(time.Now())
ctx, c := context.WithCancel(context.Background())
go TimerJob(ctx)
time.Sleep(10 * time.Second)
c()
time.Sleep(10 * time.Second)
}