教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang中timer定时器实现原理

golang中timer定时器实现原理

发布时间:2022-01-15   编辑:jiaochengji.com
教程集为您提供golang中timer定时器实现原理等资源,欢迎您收藏本站,我们将为您提供最新的golang中timer定时器实现原理资源

一般我们导入import ("time")包,然后调用time.NewTicker(1 * time.Second) 实现一个定时器:

<pre class="brush:cpp ;toolbar: true; auto-links: false;">func timer1() { timer1 := time.NewTicker(1 * time.Second) for { select { case <-timer1.C: xxx() //执行我们想要的操作 } } }</pre>

再看看timer包中NewTicker的具体实现:

<pre class="brush:cpp ;toolbar: true; auto-links: false;">func NewTicker(d Duration) *Ticker { if d <= 0 { panic(errors.New("non-positive interval for NewTicker")) } // Give the channel a 1-element time buffer. // If the client falls behind while reading, we drop ticks // on the floor until the client catches up. c := make(chan Time, 1) t := &Ticker{ C: c, r: runtimeTimer{ when:   when(d), period: int64(d), f:      sendTime, arg:    c, }, } startTimer(&t.r) return t }</pre>

其中Ticker的具体struct如下:

<pre class="brush:cpp ;toolbar: true; auto-links: false;">type Ticker struct { C <-chan Time // The channel on which the ticks are delivered. r runtimeTimer }</pre>

Ticker中的C为数据类型为Time的单向管道,只能读,不能写

再分下一下runtimeTimer的参数:

<pre class="brush:cpp ;toolbar: true; auto-links: false;">r: runtimeTimer{ when:   when(d), period: int64(d), f:      sendTime, arg:    c, }</pre>

其中sendTime为回调函数,startTimer时候注册的,arg为回调函数需要的参数arg

<pre class="brush:cpp ;toolbar: true; auto-links: false;">startTimer(&t.r)</pre>

再进一步看看startTimer的实现:

<pre class="brush:cpp ;toolbar: true; auto-links: false;">func sendTime(c interface{}, seq uintptr) { // Non-blocking send of time on c. // Used in NewTimer, it cannot block anyway (buffer). // Used in NewTicker, dropping sends on the floor is // the desired behavior when the reader gets behind, // because the sends are periodic. select { case c.(chan Time) <- Now(): default: } }</pre>

通过往管道里面写时间,注意我们<span style="line-height: 22.5px;">Ticker结构里面的C是单向管道,只能读不能写,那要怎么写数据了</span>

<span style="line-height: 22.5px;">通过类型转化,因为</span>channel是一个原生类型,因此不仅支持被传递,还支持类型转换,装换成双向的管道channel,往里面

写数据,用户API那边提供的是单向管道,用户只能就只能读数据,就相当于一层限制


最后,调用执行具体xxx函数,实现定时执行某些事件的功能:

<pre class="brush:cpp ;toolbar: true; auto-links: false;">for {     select { case <-timer1.C:   xxxx()      }    }</pre>


<span style="line-height: 22.5px;"/>


到此这篇关于“golang中timer定时器实现原理”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
golang append性能_GoLang定时器实现原理
Go Ticker实现原理剖析(轻松掌握Ticker实现原理)
C#中Timer定时器控件实例与原理解析
Python中的简单定时器
golang中timer定时器实现原理
C#中Timer定时器控件的使用方法
C#各种定时器Timer类的区别与使用介绍
C# Timer定时器控件运行时需要修改系统时间的问题
C#中定时器控件Timer学习参考
GoLang定时器实现原理

[关闭]
~ ~