go corn定时器
生活随笔
收集整理的這篇文章主要介紹了
go corn定时器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡言
1. 雖然golang提供了簡單的定時器實現,比如time.NewTicker,但是只能功能過于簡單
2. 沒法做一些規則化,比如每隔多久觸發,指定日期觸發等等
3. 這里介紹一個第三方的定時器包,github.com/robfig/cron,功能強大,接口簡單
4. 注意:linux 中的 cron 只能精確到分鐘,無法精確到秒,想實現精確到秒的定時器只能自己實現
?
例子1(1秒觸發一次的定時器):
執行結果如下圖(我們是每隔一秒打印一次數字):
代碼如下圖:
package main import ("fmt""github.com/robfig/cron" )// 返回一個支持至 秒 級別的 cron func newWithSeconds() *cron.Cron {secondParser := cron.NewParser(cron.Second | cron.Minute |cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)return cron.New(cron.WithParser(secondParser), cron.WithChain()) }func main() {i := 0c := newWithSeconds()spec := "0/1 * * * * ?" //一秒執行一次回調c.AddFunc(spec, func() {i++fmt.Println("cron running:", i)})c.Start()select {} }例子2(每隔兩分鐘執行一次,分鐘里的第5秒)
代碼如下
package main import ("fmt""time""github.com/robfig/cron" )// 返回一個支持至 秒 級別的 cron func newWithSeconds() *cron.Cron {secondParser := cron.NewParser(cron.Second | cron.Minute |cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)return cron.New(cron.WithParser(secondParser), cron.WithChain()) }func main() {i := 0c := newWithSeconds()spec := "5 */2 * * * ?" //每隔兩分鐘,5秒的時候觸發c.AddFunc(spec, func() {i++fmt.Printf("time=%v, cron running=%v \n", time.Now(), i)})c.Start()select {} }?
cron表達式的各個字段解釋
| 秒(Seconds) | Yes | 0-59 | * / , - |
| 分(Minutes) | Yes | 0-59 | * / , - |
| 小時(Hours) | Yes | 0-23 | * / , - |
| 一個月中的某一天(Day of month) | Yes | 1-31 | * / , - ? |
| 月(Month) | Yes | 1-12 or JAN-DEC | * / , - |
| 星期幾(Day of week) | Yes | 0-6 or SUN-SAT | * / , - ? |
注意:月和星期字段值不區分大小寫。'SUN'、'Sun'和'sun'都是一樣的
預定義,我們可以使用這些預定義來代替復雜的cron表達式
| @yearly (or @annually) | 每年1月1日凌晨執行一次 | 0 0 0 1 1 * |
| @monthly | 每個月第一天的凌晨執行一次 | 0 0 0 1 * * |
| @weekly | 每周周六的凌晨執行一次 | 0 0 0 * * 0 |
| @daily (or @midnight) | 每天凌晨0點執行一次 | 0 0 0 * * * |
| @hourly | 每小時執行一次 | 0 0 * * * * |
總結
以上是生活随笔為你收集整理的go corn定时器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: go 打印 %v %+v %#v 的区别
- 下一篇: centos7 redis5.0以后版本