GO by example, part 4

This commit is contained in:
2022-01-11 14:50:17 +01:00
parent c5983176c5
commit 5d7e654fa1
10 changed files with 428 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
package main
import (
"fmt"
"time"
)
// built-in timer and ticker features
func main() {
// timers represent a single event in the future
// tell the timer how long to wait and it provides a channel that will be notified at that time
timer1 := time.NewTimer(2 * time.Second)
// <-timer1.C blocks on the timers channel C until it sends a value indicating that the timer fired
<-timer1.C
fmt.Println("Timer 1 fired")
// to wait, you could have used time.Sleep
timer2 := time.NewTimer(time.Second)
go func() {
<-timer2.C
fmt.Println("Timer 2 fired")
}()
// one can cancel the timer before it fires
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")
}
// give the timer2 enough time to fire, if it ever was going to, to show it is in fact stopped
time.Sleep(2 * time.Second)
}