This commit is contained in:
Mark McGranaghan 2012-10-09 11:40:40 -07:00
parent bdadb4059e
commit 5bb6b01f89
4 changed files with 23 additions and 7 deletions

View File

@ -1,20 +1,33 @@
// ## Tickers
// [Timers](timers.html) are for when you want to do
// something once in the future - tickers are for when you
// want to do something repeatedly at regular intervals.
// Here's an example of a ticker that ticks periodically
// until we stop it.
package main
import "time"
import "fmt"
func main() {
// Tickers use a similar mechanism to timers: a
// chanel that is sent values. Here we'll use the
// `range` builtin on the channel to iterate over
// the values as they arrive every 500ms.
ticker := time.NewTicker(time.Millisecond * 500)
go func() {
for t := range ticker.C {
fmt.Println("Tick at", t)
}
}()
// Tickers can be stopped like timers. Once a ticker
// is stopped it won't receive any more values on its
// channel. We'll stop ours after 1500ms.
time.Sleep(time.Millisecond * 1500)
ticker.Stop()
fmt.Println("Ticker stopped")
}
// todo: pull from blog post

View File

@ -1,3 +1,5 @@
# When we run this program the ticker should tick 3 times
# befor we stop it.
$ go run tickers.go
Tick at 2012-09-23 11:29:56.487625 -0700 PDT
Tick at 2012-09-23 11:29:56.988063 -0700 PDT

View File

@ -3,7 +3,8 @@
// We often want to execute Go code at some point in the
// future, or repeatedly at some interval. Go's built-in
// timer and ticker features make both of these tasks
// easy. First we'll look at timers.
// easy. We'll look first at timers and then
// at [tickers](tickers.html).
package main
@ -27,15 +28,12 @@ func main() {
// If you just wanted to wait, you could have used
// `time.Sleep`. One reason a timer may be useful is
// that you can cancel the timer before it expires.
// Here's an example of that.
timer2 := time.NewTimer(time.Second)
go func() {
<-timer2.C
fmt.Println("Timer 2 expired")
}()
// In this case we'll cancel the timer before it has a
// change to expire (`.Stop()` would return `false` if
// we tried to cancel it after it expired).
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")

View File

@ -1,3 +1,6 @@
// The first timer will expire ~2s after we start the
// program, but the second should be stopped before it has
// a chance to expire.
$ go run timers.go
Timer 1 expired
Timer 2 stopped