go 计时器------time,Ticker

ticker结构,一个有计时的通道的定时器,到一个时间点就触发。

// A Ticker holds a channel that delivers `ticks' of a clock
// at intervals.
type Ticker struct {
	C <-chan Time // The channel on which the ticks are delivered.
	r runtimeTimer
}

先来一个例子:这里实现了俩个计时,一个是每2秒打印一个tick,还有一个是到20秒之后结束。

package main

import (
	"fmt"
	"time"
)

func main(){
	tim:=time.Tick(time.Second*20)
	tc:=time.NewTicker(time.Second*2)
	defer tc.Stop()
	done:=make(chan bool)
	var i=0
	 go func() {
		 for{
			 select {
			 case <- tim:
				 fmt.Printf("shijian" )
				 tc.Stop()
				 done<-true
			 case <-tc.C:
				 i++
				 fmt.Printf("tick ,%v\n",i )

			 }
		 }
	 }()
	<-done
	fmt.Printf("end",i )
}

简单说一下俩个计时的不同实现

tc:=time.NewTicker(time.Second*2)
defer tc.Stop()

记得把ticker关闭,这边是生成一个Ticker,Ticker本身就带有一个channel,用来阻塞的,当时间到了,select的触发第二个case(也不算是触发,select在for下循环的,如果某个case的channel不阻塞的话执行后面的操作)

tim:=time.Tick(time.Second*20)
// Tick is a convenience wrapper for NewTicker providing access to the ticking
// channel only. While Tick is useful for clients that have no need to shut down
// the Ticker, be aware that without a way to shut it down the underlying
// Ticker cannot be recovered by the garbage collector; it "leaks".
// Unlike NewTicker, Tick will return nil if d <= 0.
func Tick(d Duration) <-chan Time {
	if d <= 0 {
		return nil
	}
	return NewTicker(d).C
}

还有一个20秒的定时器,使用time包的Tick实现的,它的方法如上。可以看一下它的说明,简单来说就是生成一个Ticker的channel,不通过Ticker结构来。
所以代码中timtc.C都是一个channel。
再通过

 go func() {
		 for{
			 select {
			 case <- tim:
				 fmt.Printf("shijian" )
				 tc.Stop()
				 done<-true
			 case <-tc.C:
				 i++
				 fmt.Printf("tick ,%v\n",i )

			 }
		 }
	 }()

起一个携程,让它一直跑。当到了20秒,通过done向主协程传送信息,结束。
主要是用了select机制。
贴个结果
在这里插入图片描述
补充一个常用的定时方法

fmt.Printf("end\n",time.Now() )
time.AfterFunc(time.Second*2, func() {
		fmt.Print("after\n" ,time.Now())
})
time.Sleep(time.Second*3)//为了不让主线程退出,睡一会

在之前的main中跑一下。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值