golang-Timers and Tickers

本文通过四个示例介绍了Go语言内置的定时器(timer)和计时器(ticker)的使用方法,包括如何实现延迟执行、取消定时任务、周期性执行任务以及定时器与其他并发结构的交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值