golang-Timers and Tickers

Go内置的timer和ticker实现
1. 在未来某个时刻执行某段代码
2. 指定间隔周期性的执行某个任务

example/test1.go

package main

import (
    "fmt"
    "time"
)

func durationExec() {
    timer := time.NewTicker(time.Second * 2)
    <- timer.C
    println("Timer expired")
}

func cancelExec() {
    timer := time.NewTimer(time.Second * 2)

    go func () {
        fmt.Println("goroutine start")
        <- timer.C
        fmt.Println("Timer expired")
    }()
    time.Sleep(1)
    fmt.Println("goroutine stop start")
    stop := timer.Stop()

    fmt.Println("Timer cancelled:",stop)
}

func repeateIntervalExec() {
    ticker := time.NewTicker(time.Millisecond * 500)

    go func() {
        for t := range ticker.C {
            fmt.Println("Tick at:",t)
        }
    }()

    time.Sleep(time.Millisecond * 1500)
    ticker.Stop()
    fmt.Println("Ticker stopped")
}


func hookExec() {
    timeChan := time.NewTimer(time.Second).C

    tickChan := time.NewTicker(time.Millisecond * 500).C

    doneChan := make(chan bool)
    go func() {
        time.Sleep(time.Second * 2)
        doneChan <- true
    }()

    for {
        select {
        case <- timeChan:
            fmt.Println("Timer expired")
        case <- tickChan:
            fmt.Println("Ticker ticked")
        case <- doneChan:
            fmt.Println("Done")
            return
        }
    }
}

func main() {
    fmt.Println("\ntime example-1")

    //实现延迟执行的效果
    durationExec()

    fmt.Println("\ntime example-2")
    //取消timer
    cancelExec()

    fmt.Println("\ntime example-3")
    //间隔周期性执行
    repeateIntervalExec()

    fmt.Println("\ntime example-4")
    //与其他交互
    hookExec()

}

output

# go run test1.go
time example-1
Timer expired

time example-2
goroutine start
goroutine stop start
Timer cancelled: true

time example-3
Tick at: 2018-03-11 00:42:06.752574836 +0800 CST m=+2.500685090
Tick at: 2018-03-11 00:42:07.252591072 +0800 CST m=+3.000701322
Ticker stopped

time example-4
Tick at: 2018-03-11 00:42:07.752586713 +0800 CST m=+3.500696965
Ticker ticked
Timer expired
Ticker ticked
Ticker ticked
Ticker ticked
Done

参考
https://mmcgrana.github.io/2012/09/go-by-example-timers-and-tickers.html

相关文章

程序目录结构 简单实现,用户登录后返回一个jwt的token,下次请求带上token请求用户信息接口并返回信息...
本篇博客的主要内容是用go写一个简单的Proof-of-Work共识机制,不涉及到网络通信环节,只是一个本地的简...
简介 默克尔树(MerkleTree)是一种典型的二叉树结构,其主要特点为: 最下面的叶节点包含存储数据或其...
接下来学习并发编程, 并发编程是go语言最有特色的地方, go对并发编程是原生支持. goroutine是go中最近本...
先普及一下, 什么是广度优先搜索 广度优先搜索类似于树的层次遍历。从图中的某一顶点出发,遍历每一个顶...
第一天: 接口的定义和实现 第二天: 一. go语言是面向接口编程. 在学习继承的时候说过, go语言只有封装,...