1.9.2 创建定时通知

  1. 使用Go语言通道实现一个一次性的定时通知器

    func TimeLong(d time.Duration) <-chan struct{} {
    	ch := make(chan struct{}, 1)
    	go func() {
    		time.Sleep(d)
    		ch <- struct{}{}
    	}()
    
    	return ch
    }
    
    func main() {
    
    	fmt.Println("你好~")
    	<-TimeLong(time.Second)
    	fmt.Println("过1秒后继续展示")
    	<-TimeLong(time.Second)
    	fmt.Println("再过1秒后显示:")
    
    }

    结果:

    你好~
    过1秒后继续展示
    再过1秒后显示:
  2. 事实上,time标准库包中的After()函数提供了和上例中TimeLong()函数相同的功能,在实际开发中,尽量使用time.After()函数以使代码看上去更简洁

  3. 注意:

    1. 调用<-time.After()函数将使当前携程进入阻塞状态,而调用time.Sleep()函数不会如此

    2. <-time.After()函数经常会被使用在超时机制实现中

Last updated