1. 程式人生 > >Go Example--定時器

Go Example--定時器

package main

import (
    "fmt"
    "time"
)

func main() {
    //定時器2s
    timer1 := time.NewTimer(time.Second * 2)
    //讀取通道,阻塞2s
    <-timer1.C

    fmt.Println("Timer 1 expired")

    timer2 := time.NewTimer(time.Second)
    go func() {
        <-timer2.C
        fmt.Println("Timer 2 expired")
    }()
    //停止定時器
    stop2 := timer2.Stop()
    if stop2 {
        fmt.Println("Timer 2 stoped")
    }
}