Timers

The utility that can replace the default clause in a select statement is the time.Timer type. This contains a receive-only channel that will return a time.Time value after the duration specified during its construction, using time.NewTimer:

func main() {
ch1, ch2 := make(chan int), make(chan int)
a, b := 2, 10
go func() { <-ch1 }()
go func() { ch2 <- a }()
t := time.NewTimer(time.Nanosecond)
select {
case ch1 <- b:
fmt.Println("ch1 got a", b)
case v := <-ch2:
fmt.Println("ch2 got a", v)
case <-t.C:
fmt.Println("too slow")
}
}

The full example is available at https://play.golang.org/p/vCAff1kI4yA.

A timer exposes a read-only channel, so it's not possible to close it. When created with time.NewTimer, it waits for the specified duration before firing a value in the channel.

The Timer.Stop method will try to avoid sending data through the channel and return whether it succeeded or not. If false is returned after trying to stop the timer, we still need to receive the value from the channel before being able to use the channel again.

 Timer.Reset restarts the timer with the given duration, and returns a Boolean as it happens with Stop. This value is either true or false:

  • true when the timer is active
  • false when the timer was fired or stopped

We will test these functionalities with a practical example:

t := time.NewTimer(time.Millisecond)
time.Sleep(time.Millisecond / 2)
if !t.Stop() {
panic("it should not fire")
}
select {
case <-t.C:
panic("not fired")
default:
fmt.Println("not fired")
}

We are creating a new timer of 1ms. Here, we wait 0.5ms and then stop it successfully:

if t.Reset(time.Millisecond) {
panic("timer should not be active")
}
time.Sleep(time.Millisecond)
if t.Stop() {
panic("it should fire")
}
select {
case <-t.C:
fmt.Println("fired")
default:
panic("not fired")
}

The full example is available at https://play.golang.org/p/ddL_fP1UBVv.

Then, we are resetting the timer back to 1ms and waiting for it to fire, to see whether Stop returns false and the channel gets drained.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.206