time.Tick() Function in Golang With Examples
Last Updated :
21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Tick() function in Go language is a utility wrapper for NewTicker function. It only allows access to the ticking channel. In addition, Tick is beneficial for clients who don’t require to shut down the Ticker. And Tick method returns nil if the duration stated is less than or equal to 0. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func Tick(d Duration) <-chan Time
Here, d is the duration of time for ticker to tick, and chan is the ticking channel.
Note: Tickers are used to do something frequently at regular intervals of the stated time.
Return Value: It returns current date and actual time after regular interval of time. And returns nil if d <= 0.
Example 1:
package main
import (
"fmt"
"time"
)
func UTCtime() string {
return ""
}
func main() {
for tick := range time .Tick(3 * time .Second) {
fmt.Println(tick, UTCtime())
}
}
|
Output:
2020-04-02 03:16:22.27131713 +0000 UTC m=+3.000249815
2020-04-02 03:16:25.271334601 +0000 UTC m=+6.000267330
2020-04-02 03:16:28.271312516 +0000 UTC m=+9.000245191
2020-04-02 03:16:31.271369788 +0000 UTC m=+12.000302595
2020-04-02 03:16:34.271309254 +0000 UTC m=+15.000241952
2020-04-02 03:16:37.271324182 +0000 UTC m=+18.000256858
2020-04-02 03:16:40.271322789 +0000 UTC m=+21.000255504
2020-04-02 03:16:43.271295568 +0000 UTC m=+24.000228305......so on
Here, we have used the range keyword in order to iterate over the channel. Here, the current date and time are returned after a regular interval of time. So, the output is different at different runs. And here the loop doesn’t stops until you terminate it.
Example 2:
package main
import (
"fmt"
"time"
)
func UTCtime() string {
return ""
}
func main() {
for tick := range time .Tick(-1 * time .Second) {
fmt.Println(tick, UTCtime())
}
}
|
Output:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive (nil chan)]:
main.main()
/home/runner/SociableInsubstantialCommunication/main.go:23 +0x149
Here, in the above code, the duration stated is negative so, nil is returned and the error occurs.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...