I'm not entirely sure, but my intuition says that using `time.After` like 
that with pending sends from another goroutine will cause that goroutine to 
leak. A better solution may be to use the `WithTimeout` functionality of 
the `context` package and then periodically check the `Done()` channel to 
see if the timeout has expired. It works something like this if you imagine 
`HeavyWork` is a call to an external API: 
https://play.golang.org/p/DRtgNBLnE5 .

On Sunday, August 6, 2017 at 3:53:36 AM UTC-4, Abhijit Desai wrote:
>
> Can you please help with below code to get output at specific cutoff time 
> and exit
>
> Thanks in advance
>
> Abhi
>
>
>
> package main
>
> import "time"
> import "fmt"
>
> func main() {
>
>     c1 := make(chan string)
>     
>     go func() { //Sending data after certain time
>   
>         c1 <- "result 1"
>
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 1 sec"
>
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 2 sec"
>
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 3 sec"
>
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 4 sec"
>
>         time.Sleep(time.Second * 1)
>         c1 <- "result 2 afer 5 sec"
>     }()
>
>     select {
>         case <-time.After(time.Second * 4): { //cut off 4s and return the 
> value
>             res := <-c1                    
>             fmt.Println(res)  // expecting result "result 2 afer 3 sec" 
> but returning "result 1"
>         }
>     }
> }
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to