0%

Go 的 Cron

在 go 中使用 cron

官方文档 - https://pkg.go.dev/github.com/robfig/cron#section-readme

这篇文章写的也不错 - https://segmentfault.com/a/1190000023029219

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
"fmt"
"time"

"github.com/robfig/cron/v3"
)

func main() {
c := cron.New()

c.AddFunc("@every 1s", func() {
fmt.Println("tick every 1 second")
})

c.Start()
time.Sleep(time.Second * 5)
}

更新到V3,要注意文档中说的

The v1 branch accepted an optional seconds field at the beginning of the cron spec. This is non-standard and has led to a lot of confusion. The new default parser conforms to the standard as described by the Cron wikipedia page.

UPDATING: To retain the old behavior, construct your Cron with a custom parser:

1
2
3
4
5
6
7
// Seconds field, required
cron.New(cron.WithSeconds())

// Seconds field, optional
cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)))