Golang time.Time.NewTimer(), Stop() functions and time.Timer type example
package time
Golang time.Time.NewTimer(), Stop() functions and time.Timer type usage example.
package main
import (
"fmt"
"time"
)
func main() {
duration := time.Duration(5) * time.Second
timer := time.NewTimer(duration)
go func() {
<-timer.C
fmt.Println("Timer expired")
}()
time.Sleep(time.Duration(3) * time.Second)
stop := timer.Stop()
fmt.Println("Timer stopped before expired : ", stop)
}
Output :
Timer stopped before expired : true
If you increase the time.Sleep duration to above 5 seconds. The timer will be stopped before expiring.
package main
import (
"fmt"
"time"
)
func main() {
duration := time.Duration(5) * time.Second
timer := time.NewTimer(duration)
go func() {
<-timer.C
fmt.Println("Timer expired")
}()
time.Sleep(time.Duration(6) * time.Second)
stop := timer.Stop()
fmt.Println("Timer stopped before expired : ", stop)
}
Output :
Timer expired
Timer stopped before expired : false
References :
Advertisement
Something interesting
Tutorials
+8.2k How to show different content from website server when AdBlock is detected?
+4.9k Nginx and PageSpeed build from source CentOS example
+9.7k Golang : Detect number of active displays and the display's resolution
+16k Golang : Generate universally unique identifier(UUID) example
+8.8k Android Studio : Image button and button example
+11.2k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+5.4k Unix/Linux/MacOSx : How to remove an environment variable ?
+17.7k Golang : [json: cannot unmarshal object into Go value of type]
+6.2k PHP : Get client IP address
+5k Golang : Constant and variable names in native language
+6.1k Java : Human readable password generator
+17.5k Golang : Clone with pointer and modify value