Created
July 3, 2021 06:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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