GO by example, part 4
This commit is contained in:
31
5-go-by-example/34-tickers.go
Normal file
31
5-go-by-example/34-tickers.go
Normal 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")
|
||||
}
|
||||
Reference in New Issue
Block a user