Preface
Timers are widely used in Go language applications. The Go language standard library provides two types of timers, one is a one-time timer.Timer
, the other is a periodic timerTicker
. This article mainly looks atTicker
If you need it, please refer to the following content, I hope it will be helpful to you.
Ticker
Ticker is a periodic timer, that is, periodically triggering an event. It will send an event (current time) to the channel at an interval, and the receiver of the channel can read the event from the channel at a fixed time interval. Pass events out through the pipeline provided by Ticker itself.
Application example
package main import ( "fmt" "time" ) func main() { ticker := ( * 1) //Create a periodic timer i := 1 for { (i, "====>", <-) if i == 5 { () //Stop the timer break } i++ } }
Output result:
1 ====> 2022-08-24 15:58:38.971837 +0800 CST m=+1.001366085
2 ====> 2022-08-24 15:58:39.971154 +0800 CST m=+2.000695418
3 ====> 2022-08-24 15:58:40.971633 +0800 CST m=+3.001185460
4 ====> 2022-08-24 15:58:41.97109 +0800 CST m=+4.000654126
5 ====> 2022-08-24 15:58:42.971594 +0800 CST m=+5.001169210
Create a timer
Use the NewTicker() method to create a periodic timer, the function is as follows:
func NewTicker(d Duration) *Ticker
Where parameter d is the period triggered by the timer time, which is a time period.
Stop the timer
The Stop method exposed to the outside by using the timer can stop a periodic timer. The function is as follows:
func (t *Ticker) Stop()
This method stops timing, and after stopping, no event is written into the timer's pipeline, but the pipeline is not closed.
After the pipeline is completed, it will be automatically released after the life cycle is over.
Implementation principle
Data structure
Ticker's data structure is exactly the same as Timer:
passsrc/:Ticker
DefinedTimer
Data structure:
type Ticker struct { C <-chan Time r runtimeTimer }
It provides achannel
, no data is written before the timing time arrivesWill be blocked until time arrives
channel
Write to the system time, blocking is released, and data can be read from it, which is an event.
We can understandInstantly facing
Ticker
User's,It is an underlying timer implementation.
runtimeTimer
RuntimeTimer is the carrier of the task, which is used to monitor timing tasks. Every time a Timer is created, a runtimeTimer variable is created and then handed over to the system for monitoring. We achieve the purpose of timing by setting the behavior after the runtimeTimer expires.
The source code package src/time/:runtimeTimer defines its data structure:
type runtimeTimer struct { tb uintptr //Storing the array address of the current timer i int // Storing the array subscript of the current timer when int64 // The current timer trigger time period int64 // The current timer cycle trigger interval f func(interface{}, uintptr) // Functions executed when the timer is triggered arg interface{} // When the timer is triggered, the parameter passed by the function is executed seq uintptr // Parameter 2 of the function is passed when the timer is triggered (this parameter is only used in network sending and receiving scenarios)}
Create a Ticker
func NewTicker(d Duration) *Ticker { if d <= 0 { panic(("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), // The important area between Ticker and Timer is to provide the period parameter, which determines whether the timer is one-time or periodic. f: sendTime, arg: c, }, } startTimer(&) return t }
NewTicker() constructs a Ticker, and then passes it to the system coroutine maintenance through startTimer().
where period is the period triggered by the event.
Stop Ticker
Stop the Ticker and just remove the Ticker from the system coroutine.
func (t *Ticker) Stop() { stopTimer(&) }
stopTicker() notifies the system coroutine to remove the Ticker, which means no longer monitors. System coroutines simply remove Ticker and do not close the pipeline to avoid user coroutine read errors.
Notice:
Ticker must be released after use, otherwise resource leakage will occur, which will continue to consume CPU resources and eventually exhaust the CPU.
ticker := (1 * ) defer ()
Difference between Ticker and Timer
- Ticker - Repeat tasks are very useful
- Timer - for performing one-time tasks
summary
Ticker's related content is summarized as follows:
- Use() to create a timer;
- Use Stop() to stop a timer;
- The timer must be released after it is used, otherwise resource leakage will occur;
If you need to know about Timer, you can read this articlehttps:///article/
The above is a detailed explanation of the usage and implementation principles of Go Ticker periodic timer. For more information about Go Ticker periodic timer, please pay attention to my other related articles!