Skip to content

Instantly share code, notes, and snippets.

@DanyelMorales
Created January 24, 2022 06:27
Show Gist options
  • Save DanyelMorales/902374e7a250716aa98c688920bb0782 to your computer and use it in GitHub Desktop.
Save DanyelMorales/902374e7a250716aa98c688920bb0782 to your computer and use it in GitHub Desktop.
Heartbeat healthcheck
func health() {
dowork := func(done <-chan interface{}, pulseInterval time.Duration) (<-chan interface{}, <-chan time.Time) {
hearthbeat := make(chan interface{})
results := make(chan time.Time)
go func() {
defer close(hearthbeat)
defer close(results)
pulse := time.Tick(pulseInterval)
workGen := time.Tick(2 * pulseInterval)
sendPulse := func() {
select {
case hearthbeat <- struct{}{}:
default:
}
}
sendResult := func(r time.Time) {
for {
select {
case <-done:
return
case <-pulse:
sendPulse()
case results <- r:
return
}
}
}
for {
select {
case <-done:
return
case <-pulse:
sendPulse()
case r := <-workGen:
sendResult(r)
}
}
}()
return hearthbeat, results
}
done := make(chan interface{})
time.AfterFunc(10*time.Second, func() {
close(done)
})
const timeout = 2 * time.Second
heartbeat, results := dowork(done, timeout/2)
for {
select {
case _, ok := <-heartbeat:
if ok == false {
return
}
fmt.Println("pulse")
case r, ok := <-results:
if ok == false {
return
}
fmt.Printf("results %v \n", r.Second())
case <-time.After(timeout):
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment