Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "context"
  5. "fmt"
  6. "math/rand"
  7. "time"
  8. )
  9.  
  10. func pollSource(ctx context.Context) error {
  11. errChan := make(chan error, 1)
  12. tick := time.Tick(500 * time.Millisecond)
  13. for {
  14. select {
  15. // Parent canceled this job
  16. case <-ctx.Done():
  17. return fmt.Errorf("canceled")
  18. // Got a tick, we should do something
  19. case <-tick:
  20. go func() {
  21. if err := fetch(ctx); err != nil {
  22. errChan <- err
  23. }
  24. }()
  25. // Last tick caused an error, log it
  26. case err := <-errChan:
  27. fmt.Println(err)
  28. }
  29. }
  30. }
  31.  
  32. func fetch(ctx context.Context) error {
  33. done := make(chan bool)
  34. timeout, _ := context.WithTimeout(ctx, 1*time.Second)
  35.  
  36. // Do something with latency
  37. go func() {
  38. time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
  39. fmt.Println("did something")
  40. done <- true
  41. }()
  42.  
  43. // Got a timeout! fail with a timeout error
  44. select {
  45. case <-timeout.Done():
  46. return fmt.Errorf("timed out")
  47. case <-done:
  48. return nil
  49. }
  50. }
  51.  
  52. func main() {
  53. ctx, cancel := context.WithCancel(context.Background())
  54. defer cancel()
  55. go func() { fmt.Println(pollSource(ctx)) }()
  56. time.Sleep(10 * time.Second)
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement