Created
June 10, 2021 08:02
-
-
Save cassc/787fed65c11ffb034e1697db713aaa45 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 main() { | |
// async_chan() | |
// timeroutTimer() | |
// cancelTimer() | |
tickTimer() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment