timers
This commit is contained in:
parent
a870b9995d
commit
eb2a1a1e85
@ -1,24 +1,43 @@
|
|||||||
// ## Timers
|
// ## Timers
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import "time"
|
import "time"
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
timer1 := time.NewTimer(time.Second)
|
|
||||||
|
// Timers represent a single event in the future. You
|
||||||
|
// tell the timer how long you want to wait, and it
|
||||||
|
// provides a channel that will be notified at that
|
||||||
|
// time. This timer will wait 2 seconds.
|
||||||
|
timer1 := time.NewTimer(time.Second * 2)
|
||||||
|
|
||||||
|
// The `<-timer1.C` blocks on the timer's channel `C`
|
||||||
|
// until it sends a value indicating that the timer
|
||||||
|
// expired.
|
||||||
<-timer1.C
|
<-timer1.C
|
||||||
fmt.Println("Timer 1 expired")
|
fmt.Println("Timer 1 expired")
|
||||||
stop1 := timer1.Stop()
|
|
||||||
fmt.Println("Timer 2 stopped:", stop1)
|
|
||||||
|
|
||||||
|
// 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.
|
||||||
timer2 := time.NewTimer(time.Second)
|
timer2 := time.NewTimer(time.Second)
|
||||||
go func() {
|
go func() {
|
||||||
<-timer2.C
|
<-timer2.C
|
||||||
fmt.Println("Timer 2 expired")
|
fmt.Println("Timer 2 expired")
|
||||||
}()
|
}()
|
||||||
stop2 := timer2.Stop()
|
|
||||||
fmt.Println("Timer 2 stopped:", stop2)
|
|
||||||
}
|
|
||||||
|
|
||||||
// todo: pull from blog post
|
// 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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
3
src/timers/timers.sh
Normal file
3
src/timers/timers.sh
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
$ go run timers.go
|
||||||
|
Timer 1 expired
|
||||||
|
Timer 2 stopped
|
@ -1,4 +0,0 @@
|
|||||||
$ go run timers.go
|
|
||||||
Timer 1 expired
|
|
||||||
Timer 2 stopped: false
|
|
||||||
Timer 2 stopped: true
|
|
Loading…
x
Reference in New Issue
Block a user