Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
15 Jul 2023 · 2 min read ·Article 26 / 119
Go

Get to know the Package Ticker in Golang

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

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

go
1func main() {
2	ticker := time.NewTicker(2 * time.Second)
3
4	for time := range ticker.C {
5		fmt.Println(time)
6	}
7}

So, this is the result of the program when it has been executed

bash
1✗ go run app.go
22023-07-14 20:01:54.791547 +0700 WIB m=+2.001171293
32023-07-14 20:01:56.791505 +0700 WIB m=+4.001184418
42023-07-14 20:01:58.791443 +0700 WIB m=+6.001177376
52023-07-14 20:02:00.791414 +0700 WIB m=+8.001202543
62023-07-14 20:02:02.791341 +0700 WIB m=+10.001184334
7^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.

Related Articles

💬 Comments