golang语言——time.After

201 阅读1分钟

time.After(d)返回的实际是Timer.C,当d时间到达时,可以通过chan获取到当前时间。

func After(d Duration) <-chan Time {
	return NewTimer(d).C
}

通过time.After可以在某个时间之后做一些处理

package main

import (
	"context"
	"fmt"
	"time"
)

func worker(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("协程将要停止...")
			return
		default:
			fmt.Println("协程工作中...")
			time.Sleep(time.Second)
		}
	}
}

func main() {
	ctx,cancel := context.WithCancel(context.Background())

	go worker(ctx)

	select {
	case <-time.After(3*time.Second):
		cancel()
	}

	time.Sleep(time.Second)
	fmt.Println("main退出")
}