Skip to content

Instantly share code, notes, and snippets.

@leonardo5621
Last active July 22, 2022 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonardo5621/907b6b89bbdc8b0710ce741cbca281c2 to your computer and use it in GitHub Desktop.
Save leonardo5621/907b6b89bbdc8b0710ce741cbca281c2 to your computer and use it in GitHub Desktop.
func (s *sub) serve(ctx context.Context, checkFrequency int) {
clock := time.NewTicker(time.Duration(checkFrequency) * time.Second)
type fetchResult struct {
fetched Item
err error
}
fetchDone := make(chan fetchResult, 1)
for {
select {
// Clock that triggers the fetch
case <-clock.C:
go func() {
fetched, err := s.fetcher.Fetch()
fetchDone <- fetchResult{fetched, err}
}()
// Case where the fetch result is
// Ready to be consumed
case result := <-fetchDone:
fetched := result.fetched
if result.err != nil {
log.Println("Fetch error: %v \n Waiting the next iteration", result.err.Error())
break
}
s.updates <-fetched
// Case where we need to close the server
case <-ctx.Done():
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment