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 :

http://golang.org/pkg/time/#Timer

http://golang.org/pkg/time/#NewTimer

Advertisement