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,31 @@
// tickers are for when you want to do something repeatedly at regular intervals
package main
import (
"fmt"
"time"
)
func main() {
// Tickers use a similar mechanism to timers: a channel that is sent values
ticker := time.NewTicker(500 * time.Millisecond)
done := make(chan bool)
go func() {
for {
select {
case <-done:
return
case t := <-ticker.C:
fmt.Println("Tick at", t)
}
}
}()
// Tickers can be stopped like timers
time.Sleep(1600 * time.Millisecond)
ticker.Stop()
done <- true
fmt.Println("Ticker stopped")
}