In general we import an import ("Time") package and then call time. Newticker (1 * time. Second) implements a timer:
Func timer1 () {timer1: = time. Newticker (1 * time. Second) for {select {case <-timer1. C:XXX ()//Perform the action we want}}}
Then look at the specific implementation of the Newticker in the timer package:
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 Whil e Reading, we drop ticks//on the until of the client catches up.c: = Make (chan time, 1) t: = &ticker{c:c,r:runtim Etimer{when:when (d), Period:int64 (d), F:sendtime,arg:c,},}starttimer (&T.R) return T}
The specific struct of ticker is as follows:
Type Ticker struct {C <-chan time//The channel on which the ticks is DELIVERED.R Runtimetimer}
C in Ticker is a one-way pipe with data type time, read only, cannot write
Let's split the Runtimetimer parameter:
R:runtimetimer{when:when (d), Period:int64 (d), F:sendtime,arg:c,}
Where Sendtime is the callback function, Starttimer is registered, ARG is the parameter arg required by the callback function
Starttimer (&T.R)
Take a closer look at the implementation of Starttimer:
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 is Periodic.select {case C. (Chan time) <-now ():d Efault:}}
By writing time into the pipeline, note that the C in our ticker structure is a one-way pipe, can only read and write, how to write the data
by type conversion, because the channel is a native type, it is not only supported to be passed, it also supports type conversion, and is replaced by a two-way channel channel, which
Write data, the user API over there is a one-way pipeline, the user can only read data, is equivalent to a layer of restrictions
Finally, the call executes the specific XXX function, which implements the function of timing certain events:
For {select {case <-timer1. C:xxxx ()}}
The implementation principle of timer timer in Golang