Introduction to the time.Ticker package
This Golang package is a package that is used to repeat certain events which will continue to be repeated for a certain time. When this ticker has expired
it will send a trigger or signal to the channel.
Why should we use time.Ticker?
This package is indeed conditional where we need certain events where we want to change a variable or whatever and it always repeats itself over a certain period of time.
Method Usage
Some methods that we must understand:
time.NewTicker()
is used to initialize the event process which we will repeat within a certain time period.time.Stop()
is used to stop quickly before the specified time period is complete.
Time.Ticker implementation and samples
OK, let’s just carry out the implementation so that it can be depicted directly in the code below
func main() {
ticker := time.NewTicker(2 * time.Second)
for time := range ticker.C {
fmt.Println(time)
}
}
So, this is the result of the program when it has been executed
✗ go run app.go
2023-07-14 20:01:54.791547 +0700 WIB m=+2.001171293
2023-07-14 20:01:56.791505 +0700 WIB m=+4.001184418
2023-07-14 20:01:58.791443 +0700 WIB m=+6.001177376
2023-07-14 20:02:00.791414 +0700 WIB m=+8.001202543
2023-07-14 20:02:02.791341 +0700 WIB m=+10.001184334
^Csignal: interrupt
Conclusion
So we can learn that we can use the time.Ticker
package for repetitions that are needed within a certain time, so for example, if we want to carry out a process every 1 second, we can process a certain function, of course by using time.Ticker
.