First, the Knowledge point
The class library used by the Golang timer is "time", referencing the official documentation to create a timer. The official offers two ways to create a timer, respectively:
1) Func Afterfunc (d Duration, F func ()) *timer This method probably means that the F function is executed after the D time interval.
2) Func Newtimer (d Duration) *timer This function means to create a timer every past D interval to send the current time to the channel inside the timer.
3) Add a little bit of Chan's knowledge, Channel (channel) is the Golang inside the thread communication channels. It is divided into buffered channels and non-buffered channels. Chan can also be created as only input channels or read-only channels or readable writable channels. Example:
CH: = make (chan int) unbuffered channel (readable writable channel)
CH: = Make (chan int, 10) buffered to 10 channel (readable writable channel)
CH: = make (chan<-int) unbuffered channel (write-only channel)
CH: = make (<-chan int) unbuffered channel (read-only channel)
Second, practice
Continue on to a demo requesting weather. We regularly get the latest weather every 10 minutes.
Create timer execution time is 10 minutes apart:
timer := time.NewTicker(10* time.Minute)for { <-timer.C rlt, err := doHttpGetRequest("https://restapi.amap.com/v3/weather/weatherInfo?key=你的高德key&city=110101") if err != nil { fmt.Println("net req error") } else { fmt.Println(rlt) }}
In the above code, there is a line of <-timer. C This statement, first we look at the data structure of the timer is as follows:
type Timer struct { C <-chan Time // contains filtered or unexported fields}
There is one channel C variable that can only be written to in the timer. We are using the Func Newtimer (d Duration) *timer function to create the timer. So our timer is to write the current time to this channel C every 10 minutes. We <-timer this line in the code. c is just to read the value of the channel C. Prevents threads from blocking and the timer does not function properly.
PS: A more detailed introduction to Chan reference