golang定时器


Posted in Golang onApril 14, 2022

定时器1-"*/5 * * * * *"

package main
import (
	"fmt"

	"github.com/robfig/cron"
)
//主函数
func main() {
	cron2 := cron.New() //创建一个cron实例
	//执行定时任务(每5秒执行一次)
	err:= cron2.AddFunc("*/5 * * * * *", print5)
	if err!=nil{
		fmt.Println(err)
	}
	//启动/关闭
	cron2.Start()
	defer cron2.Stop()
	select {
	//查询语句,保持程序运行,在这里等同于for{}
	}
}
//执行函数
func print5()  {
	fmt.Println("每5s执行一次cron")
}

设置说明

┌─────────────second 范围 (0 - 60)
 │ ┌───────────── min (0 - 59)
 │ │ ┌────────────── hour (0 - 23)
 │ │ │ ┌─────────────── day of month (1 - 31)
 │ │ │ │ ┌──────────────── month (1 - 12)
 │ │ │ │ │ ┌───────────────── day of week (0 - 6) (0 to 6 are Sunday to
 │ │ │ │ │ │                  Saturday)
 │ │ │ │ │ │
 │ │ │ │ │ │
 * * * * * *

星号(*) :表示 cron 表达式能匹配该字段的所有值。如在第5个字段使用星号(month),表示每个月

斜线(/):表示增长间隔,如第2个字段(minutes) 值是 3-59/15,表示每小时的第3分钟开始执行一次,之后 每隔 15 分钟执行一次(即 3(3+0*15)、18(3+1*15)、33(3+2*15)、48(3+3*15) 这些时间点执行),这里也可以表示为:3/15

逗号(,):用于枚举值,如第6个字段值是 MON,WED,FRI,表示 星期一、三、五 执行

连字号(-):表示一个范围,如第3个字段的值为 9-17 表示 9am 到 5pm 直接每个小时(包括9和17)

问号(?):只用于 日(Day of month) 和 星期(Day of week),表示不指定值,可以用于代替 *

定时器2-Timer-Ticker

Timer  //时间到了产生一次事件
Ticker  //时间到了循环产生事件

Timer-只执行一次

package main
import (
	"fmt"
	"time"
)
func main() {
	//创建一个定时器,设置时间为2s,2s后,往time通道写内容(当前时间)
	timer := time.NewTimer(2 * time.Second)
	fmt.Println("当前时间:", time.Now())
	//2s后,往timer.C写数据,有数据后,就可以读取
	t := <-timer.C //channel没有数据前后阻塞
	fmt.Println("t = ", t)
}

Ticker-循环执行

package main
import (
	"fmt"
	"time"
)
//验证time.NewTimer(),时间到了,只会响应一次
func main() {
	timer := time.NewTicker(1 * time.Second)
	for {
		<-timer.C
		fmt.Println("时间到")
	}
}

结果:

时间到
时间到
时间到
时间到

Timer延时功能

time.NewTimer(2 * time.Second)  //相当于time.Sleep(2 * time.Second)
func main() {
	//延时2s后打印一句话
	timer := time.NewTimer(2 * time.Second)
	<-timer.C
	fmt.Println("时间到")
}
func main() {
	<-time.After(2 * time.Second) //定时2s,阻塞2s, 2s后产生一个事件,往channel写内容
	fmt.Println("时间到")
}

停止和重置定时器

ok := timer.Reset(1 * time.Second) //重新设置为1s
timer.Stop() //停止定时器

停止:

func main() {
	timer := time.NewTimer(3 * time.Second)
	go func() {
		<-timer.C
		fmt.Println("子协程可以打印了,因为定时器的时间到")
	}()
	timer.Stop() //停止定时器
	for {
	}
}

重置:

func main() {
	timer := time.NewTimer(3 * time.Second)
	ok := timer.Reset(1 * time.Second) //重新设置为1s
	fmt.Println("ok = ", ok)
	<-timer.C
	fmt.Println("时间到")
}

定时器Ticker使用

package main
import (
	"fmt"
	"time"
)
func main() {
	ticker := time.NewTicker(1 * time.Second)
	i := 0
	for {
		<-ticker.C
		i++
		fmt.Println("i = ", i)
		if i == 5 {
			ticker.Stop()
			break
		}
	}
}

以上就是go语言定时器的功能使用示例详解的详细内容!

Golang 相关文章推荐
golang 实现对Map进行键值自定义排序
Apr 28 Golang
解决Go gorm踩过的坑
Apr 30 Golang
golang elasticsearch Client的使用详解
May 05 Golang
Golang生成Excel文档的方法步骤
Jun 09 Golang
基于Go语言构建RESTful API服务
Jul 25 Golang
Go语言应该什么情况使用指针
Jul 25 Golang
golang内置函数len的小技巧
Jul 25 Golang
golang为什么要统一错误处理
Apr 03 Golang
Go归并排序算法的实现方法
Apr 06 Golang
Golang并发工具Singleflight
May 06 Golang
基于Python实现西西成语接龙小助手
Aug 05 Golang
golang用type-switch判断interface的实际存储类型
Apr 14 #Golang
golang语言指针操作
Apr 14 #Golang
golang使用map实现去除重复数组
Apr 14 #Golang
golang生成并解析JSON
Apr 14 #Golang
Go语言 详解net的tcp服务
Apr 14 #Golang
golang连接MySQl使用sqlx库
Apr 14 #Golang
Go语言安装并操作redis的go-redis库
Apr 14 #Golang
You might like
php 无法载入mysql扩展
2010/03/12 PHP
php开启与关闭错误提示适用于没有修改php.ini的权限
2014/10/16 PHP
详解PHP中的null合并运算符
2015/12/30 PHP
深入理解PHP类的自动载入机制
2016/09/16 PHP
遍历指定目录,并存储目录内所有文件属性信息的php代码
2016/10/28 PHP
php图像验证码生成代码
2017/06/08 PHP
javascript 禁用IE工具栏,导航栏等等实现代码
2013/04/01 Javascript
js仿百度有啊通栏展示效果实现代码
2013/05/28 Javascript
js实现瀑布流的一种简单方法实例分享
2013/11/04 Javascript
jQuery中index()方法用法实例
2014/12/27 Javascript
js数组去重的5种算法实现
2015/11/04 Javascript
浅谈几种常用的JS类定义方法
2016/06/08 Javascript
AngularJS中指令的四种基本形式实例分析
2016/11/22 Javascript
jQuery插件JWPlayer视频播放器用法实例分析
2017/01/11 Javascript
利用Node.js编写跨平台的spawn语句详解
2017/02/12 Javascript
基于滚动条位置判断的简单实例
2017/12/14 Javascript
vue祖孙组件之间的数据传递案例
2020/12/07 Vue.js
使用python将mdb数据库文件导入postgresql数据库示例
2014/02/17 Python
python实现目录树生成示例
2014/03/28 Python
Python中生成器和yield语句的用法详解
2015/04/17 Python
使用rst2pdf实现将sphinx生成PDF
2016/06/07 Python
python入门基础之用户输入与模块初认识
2016/11/14 Python
python的random模块及加权随机算法的python实现方法
2017/01/04 Python
Python实现抓取网页生成Excel文件的方法示例
2017/08/05 Python
python DataFrame获取行数、列数、索引及第几行第几列的值方法
2018/04/08 Python
Python计算IV值的示例讲解
2020/02/28 Python
python批量替换文件名中的共同字符实例
2020/03/05 Python
浅谈tensorflow中dataset.shuffle和dataset.batch dataset.repeat注意点
2020/06/08 Python
Python将字典转换为XML的方法
2020/08/01 Python
Pandas之缺失数据的实现
2021/01/06 Python
CSS3 transition 实现通知消息轮播条
2020/10/14 HTML / CSS
localStorage、sessionStorage使用总结
2017/11/17 HTML / CSS
html5 canvas手势解锁源码分享
2020/01/07 HTML / CSS
党员创先争优公开承诺书
2014/03/28 职场文书
工程承诺书怎么写
2014/05/24 职场文书
群众路线教育实践活动个人对照检查材料
2014/09/22 职场文书