Golang time.Tick() is a “utility wrapper for NewTicker
function that allows access to the ticking channel.” Tickers are used to do something frequently at regular intervals of the stated time.
The channel was created over time.Tick() function will continue to tick indefinitely. To release the resources associated with the ticker, consider using time.NewTicker() instead returns a Ticker object you can stop when it’s no longer needed.
Syntax
func Tick(d Duration) <-chan Time
Parameters
It takes a Duration as an argument.
Return value
It returns a receive-only channel (<-chan Time) that sends a Time value at specified intervals.
Example 1
package main
import (
"fmt"
"time"
)
func main() {
tick := time.Tick(1 * time.Second)
for currentTime := range tick {
fmt.Println("Current time:", currentTime)
}
}
Output
Current time: 2023-03-18 01:27:15.817433 +0530 IST m=+1.001282167
Current time: 2023-03-18 01:27:16.817462 +0530 IST m=+2.001326084
Current time: 2023-03-18 01:27:17.817404 +0530 IST m=+3.001282501
Current time: 2023-03-18 01:27:18.817373 +0530 IST m=+4.001267834
Current time: 2023-03-18 01:27:19.817356 +0530 IST m=+5.001264917
Example 2
package main
import (
"fmt"
"time"
)
func periodicTask() {
fmt.Println("Periodic task executed at", time.Now())
}
func main() {
ticker := time.Tick(2 * time.Second)
for {
select {
case <-ticker:
periodicTask()
}
}
}
Output
Periodic task executed at 2023-03-18 01:35:11.649779 +0530 IST m=+2.001321209
Periodic task executed at 2023-03-18 01:35:13.649864 +0530 IST m=+4.001436834
Periodic task executed at 2023-03-18 01:35:15.649728 +0530 IST m=+6.001331168
Periodic task executed at 2023-03-18 01:35:17.64971 +0530 IST m=+8.001343918
Periodic task executed at 2023-03-18 01:35:19.649669 +0530 IST m=+10.001332668
That’s it.
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.