0xBF
0xBF

0xBF

Go Cheatsheet - Select with Timer & Ticker

0xBF's photo
0xBF

Published on Apr 22, 2021

1 min read

Select

Select channels with timeout

Use time.After

select {
case res := <-ch:
    fmt.Println(res)
case <-time.After(1 * time.Second):
    fmt.Println("timeout 1")
}

Or use time.NewTimer

timer1 := time.NewTimer(2 * time.Second)
select {
case <-quit:
case <- timer1.C:
    fmt.Println("Timeout 2")
}

Select channels with time interval

Use time.Tick

ticker := time.Tick(1 * time.Second)
for i:=0; i<10; i++ {
    select {
    case <- quit:
    case <- ticker:
        fmt.Println("ticker run at", i)
    }
}

Or use time.NewTicker

ticker := time.NewTicker(2 * time.Second)
for i:=0; i<10; i++ {
    select {
    case <- quit:
    case <- ticker.C:
        fmt.Println("ticker run at", i)
    }
}

To stop ticker, use ticker.Stop()

 
Share this