Fragment Description:



Duration, Timer amd Ticker.
3 types of the time standard library.
The current time will be sent on a channel C.
type Timer struct { C <-chan Time } The ticks are delivered on a channel C.
type Ticker struct { C <-chan Time }


timeTickerTimer

Go Playground

Last update, on 2015, Fri 30 Oct, 11:34:33

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "time"
)

func main() {
    // sign: func NewTicker(d Duration) *Ticker
    timerChan := time.NewTimer(time.Second * 1).C

    // func NewTimer(d Duration) *Timer
    tickerChan := time.NewTicker(time.Millisecond * 500).C
    doneChan := make(chan bool)
    go func() {
        time.Sleep(time.Second * 2)
        doneChan <- true
    }()
    for {
        select {
        case <-timerChan:
            fmt.Println("Timer expired")
        case <-tickerChan:
            fmt.Println("Ticker ticked")
        case <-doneChan:
            fmt.Println("Done")
            return
        }
    }
}

/* Expected Output:
Ticker ticked
Timer expired
Ticker ticked
Ticker ticked
Ticker ticked
Done
*/



Comments