Skip to content

Instantly share code, notes, and snippets.

@akshaybharambe14
Created July 3, 2021 06:05
Show Gist options
  • Save akshaybharambe14/ce4b54ac8f4d065d7371d4f40b5c477c to your computer and use it in GitHub Desktop.
Save akshaybharambe14/ce4b54ac8f4d065d7371d4f40b5c477c to your computer and use it in GitHub Desktop.
Expire the IDLE worker routines if they don't receive work in specified time/ https://play.golang.org/p/UN-1GGGMfzi
// https://play.golang.org/p/hkAZVC2-H3S
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Hello, playground")
in := make(chan int, 4)
go worker(1, in)
go worker(2, in)
go func() {
time.Sleep(time.Second * 2)
in <- 1
}()
t := time.NewTimer(time.Second * 10)
<-t.C
t.Stop()
}
func worker(id int, in <-chan int) {
d := time.Second * 5
t := time.NewTicker(d)
defer func() {
t.Stop()
fmt.Printf("%d worker exited\n", id)
}()
for {
select {
case i := <-in:
fmt.Printf("received %d on worker %d\n", i, id)
// reset the ticker
t.Reset(d)
case <-t.C:
fmt.Printf("worker %d reached max idle duration, will exit\n", id)
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment