Skip to content

Instantly share code, notes, and snippets.

@cassc
Created June 10, 2021 08:07
Show Gist options
  • Save cassc/0a21d5952cdfcc7617bddd9aed99ca0b to your computer and use it in GitHub Desktop.
Save cassc/0a21d5952cdfcc7617bddd9aed99ca0b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
func timeroutTimer() {
fmt.Println("Waiting for timer")
c := time.After(10 * time.Second)
<-c
fmt.Println("Timer reached")
}
func cancelTimer() {
timer := time.NewTimer(10 * time.Second)
defer timer.Stop()
a := make(chan int)
go func() {
time.Sleep(2 * time.Second)
a <- 8
}()
select {
case <-timer.C:
fmt.Println("10 seconds reached")
case n := <-a:
// timer.Stop()
fmt.Printf("Get %d from a, cancel timer", n)
}
}
func async_chan() {
ch := make(chan int)
for i := 0; i < 10; i++ {
go func(i int) {
fmt.Printf("%v\n", i)
ch <- i
}(i)
}
for i := 0; i < 10; i++ {
<-ch
}
}
func tickTimer() {
// run at fixed interval
for now := range time.Tick(2 * time.Second) {
fmt.Println(now)
}
}
func waitAct() {
timer := time.AfterFunc(3*time.Second, func() {
fmt.Println("work in timer")
})
defer timer.Stop()
fmt.Println("timer started")
time.Sleep(5 * time.Second)
fmt.Println("exit")
}
func main() {
// async_chan()
// timeroutTimer()
// cancelTimer()
// tickTimer()
waitAct()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment