Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "context"
- "fmt"
- "math/rand"
- "time"
- )
- func pollSource(ctx context.Context) error {
- errChan := make(chan error, 1)
- tick := time.Tick(500 * time.Millisecond)
- for {
- select {
- // Parent canceled this job
- case <-ctx.Done():
- return fmt.Errorf("canceled")
- // Got a tick, we should do something
- case <-tick:
- go func() {
- if err := fetch(ctx); err != nil {
- errChan <- err
- }
- }()
- // Last tick caused an error, log it
- case err := <-errChan:
- fmt.Println(err)
- }
- }
- }
- func fetch(ctx context.Context) error {
- done := make(chan bool)
- timeout, _ := context.WithTimeout(ctx, 1*time.Second)
- // Do something with latency
- go func() {
- time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
- fmt.Println("did something")
- done <- true
- }()
- // Got a timeout! fail with a timeout error
- select {
- case <-timeout.Done():
- return fmt.Errorf("timed out")
- case <-done:
- return nil
- }
- }
- func main() {
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- go func() { fmt.Println(pollSource(ctx)) }()
- time.Sleep(10 * time.Second)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement