Ticker Stop behaviour in Golang

前端 未结 4 559
遇见更好的自我
遇见更好的自我 2020-12-25 14:48

If I am ranging over a ticker channel and call stop() the channel is stopped but not closed.

In this Example:

package main

import (
    \"time\"
            


        
4条回答
  •  长情又很酷
    2020-12-25 15:06

    you can do like this.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func startTicker(f func()) chan bool {
        done := make(chan bool, 1)
        go func() {
            ticker := time.NewTicker(time.Second * 1)
            defer ticker.Stop()
            for {
                select {
                case <-ticker.C:
                    f()
                case <-done:
                    fmt.Println("done")
                    return
                }
            }
        }()
        return done
    }
    
    func main() {
        done := startTicker(func() {
            fmt.Println("tick...")
        })
        time.Sleep(5 * time.Second)
        close(done)
        time.Sleep(5 * time.Second)
    }
    

提交回复
热议问题