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

--------------------------------------------------------------------------------------------------------------------------

Timers and Tickers

September 28 2012

If you’re interested in Go, be sure to check out Go by Example.

We often want to execute Go code at some point in the future, or repeatedly at some interval. Go’s built-in timer and ticker features make both of these tasks easy. Let’s look at some examples to see how they work.

Timers

Timers represent a single event in the future. You tell the timer how long you want to wait, and it gives you a channel that will be notified at that time. For example, to wait 2 seconds:

package main

import "time"

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

The <- timer.C blocks on the timer’s channel C until it sends a value indicating that the timer expired. You can test this by putting the code in timers1.go and running it with time and go run:

$ time go run timers1.go
Timer expired
real 0m2.113s

If you just wanted to wait, you could have used time.Sleep. One reason a timer may be useful is that you can cancel the timer before it expires. For example, try running this in timers2.go:

package main

import "time"

func main() {
timer := time.NewTimer(time.Second)
go func() {
<- timer.C
println("Timer expired")
}()
stop := timer.Stop()
println("Timer cancelled:", stop)
}
$ go run timers2.go
Timer cancelled: true

In this case we canceled the timer before it had a chance to expire (Stop() would return false if we tried to cancel it after it expired.)

Tickers

Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals. Here’s a basic example:

package main

import "time"
import "fmt" func main() {
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")
}

Try it out in tickers.go:

$ go run tickers.go
Tick at 2012-09-22 15:58:40.912926 -0400 EDT
Tick at 2012-09-22 15:58:41.413892 -0400 EDT
Tick at 2012-09-22 15:58:41.913888 -0400 EDT
Ticker stopped

Tickers can be stopped just like timers using the Stop() method, as shown at the bottom of the example.

Power of Channels

A great feature of Go’s timers and tickers is that they hook into Go’s built-in concurrency mechanism: channels. This allows timers and tickers to interact seamlessly with other concurrent goroutines. For example:

package main

import "time"
import "fmt" func main() {
timeChan := time.NewTimer(time.Second).C tickChan := time.NewTicker(time.Millisecond * 400).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
}
}
}

Try it out by running this code form channels.go:

$ go run channels.go
Ticker ticked
Ticker ticked
Timer expired
Ticker ticked
Ticker ticked
Ticker ticked
Done

In this case we see the timer, ticker, and our own custom goroutine all participating in the same select block. The combination of the Go runtime, its channel feature, and timers/tickers use of channels make this kind of cooperation very natural in Go.

You can learn more about timers, tickers, and other time-related Go features in the Gotime package docs.

go语言中的timer 和ticker定时任务的更多相关文章

  1. c语言中time相关函数

    工作中遇到的函数: int seed = time(NULL); srand(seed); signal(SIGINT, stop); signal(SIGUSR1, sig_usr1); 搜time ...

  2. C语言中,头文件和源文件的关系(转)

    简单的说其实要理解C文件与头文件(即.h)有什么不同之处,首先需要弄明白编译器的工作过程,一般说来编译器会做以下几个过程: 1.预处理阶段 2.词法与语法分析阶段 3.编译阶段,首先编译成纯汇编语句, ...

  3. C 语言中 setjmp 和 longjmp

    在 C 语言中,我们不能使用 goto 语句来跳转到另一个函数中的某个 label 处:但提供了两个函数——setjmp 和 longjmp来完成这种类型的分支跳转.后面我们会看到这两个函数在处理异常 ...

  4. c语言中的scanf在java中应该怎么表达,Scanner类。

    1 java是面向对象的语言 它没有像C语言中的scanf()函数,但是它的类库中有含有scanf功能的函数 2 java.util包下有Scanner类 Scanner类的功能与scanf类似 3 ...

  5. C语言中do...while(0)的妙用(转载)

    转载来自:C语言中do...while(0)的妙用,感谢分享. 在linux内核代码中,经常看到do...while(0)的宏,do...while(0)有很多作用,下面举出几个: 1.避免goto语 ...

  6. C语言中,定义的含义?声明的含义?它们之间的区别是什么?

    在C语言中,对于定义和声明,也许我们非常的熟悉,但不一定真正的了解! 定义的含义:所谓定义,就是创建(编译器)一个对象,为这个对象分配一块内存空间并取名,也就是我们平常所说的变量名或对象名,一旦这个名 ...

  7. C++中函数的默认参数和C语言中volatile的学习

    1.函数默认参数 1 int func(int a,int b=10) 2 { 3 return a*b; 4 } 5 6 int main() 7 { 8 int c=func(2); 9 cout ...

  8. C语言中qsort函数用法

    C语言中qsort函数用法-示例分析    本文实例汇总介绍了C语言中qsort函数用法,包括针对各种数据类型参数的排序,非常具有实用价值非常具有实用价值. 分享给大家供大家参考.C语言中的qsort ...

  9. C语言中的static 详细分析

    转自:http://blog.csdn.net/keyeagle/article/details/6708077/ google了近三页的关于C语言中static的内容,发现可用的信息很少,要么长篇大 ...

随机推荐

  1. C++学习随笔

    今天试着变了下实验二里边的有关面向对象的实验,深深地觉得我对面向对象的编程的理解还是很浅显,以至于对于对象的调用也是瞎整.居然直接就去调用继承来的函数,连生成一个对象这种基础应用都不知道.对自己的基础 ...

  2. 6-Java-C(无穷分数)

    题目描述: 无穷的分数,有时会趋向于固定的数字. 请计算[图1.jpg]所示的无穷分数,要求四舍五入,精确到小数点后5位,小数位不足的补0. 请填写该浮点数,不能填写任何多余的内容. 正确算法: 此题 ...

  3. Perl字符集就是方括号(或称中括号)里一连串可能的字符,只匹配单一字符,该单一字符可以是字符集里的任何一个,“-”在字符集里有特殊含义:表示某个范围的字符。而字符集意外的连字符不具有特殊意义。

    Perl字符集就是方括号(或称中括号)里一连串可能的字符,只匹配单一字符,该单一字符可以是字符集里的任何一个,“-”在字符集里有特殊含义:表示某个范围的字符.而字符集意外的连字符不具有特殊意义.

  4. NPOI--------------.Net操作Excel初步使用(导出)

    背景 因公司项目需要添加数据导出功能故此添加,找了几种方式发现该方式具有 无需依赖本机安装office环境,使用灵活等优点故采用此方式. 安装 Nuget 直接安装NPOI即可 使用方式 1.根据需要 ...

  5. docker centos7 配置和宿主机同网段IP

    docker centos7 配置和宿主机同网段IP 1.安装brctl 命令 # yum -y install bridge-utils 2.编辑网卡配置文件 # vi ifcfg-eno16777 ...

  6. 禁止浏览器static files缓存篇

    由于CSS/JS文件经常需要改动,前端调试时是不希望浏览器缓存这些文件的. Meta法 目前在chrome调试还没有遇到问题,好用!此方法假设浏览器是个好人!很听我们的话! <meta http ...

  7. [bzoj2806][Ctsc2012]Cheat(后缀自动机(SAM)+二分答案+单调队列优化dp)

    偷懒直接把bzoj的网页内容ctrlcv过来了 2806: [Ctsc2012]Cheat Time Limit: 20 Sec  Memory Limit: 256 MBSubmit: 1943   ...

  8. C#基础学习(一)

    ---恢复内容开始--- 1.最近被安排去做C#开发,然后开始一连串的看文档·看视屏,发现学C#给自己补了很多基础,C#每个函数变量什么都要先声名,而python可以直接定义: 一.数据类型 1.整数 ...

  9. c++基础_字符串对比

    #include <iostream> #include <string.h> #include <algorithm> using namespace std; ...

  10. 关于测试驱动的开发模式以及实战部分,建议看《Python Web开发测试驱动方法》这本书

    关于测试驱动的开发模式以及实战部分,建议看<Python Web开发测试驱动方法>这本书