robfig/cron 支持cron 和 固定时间

最后更新于:2022-04-02 02:40:08

[TOC] > [github](https://github.com/robfig/cron) ## 安装 ``` go get github.com/robfig/cron/v3@v3.0.0 ``` ## 实例 ### 按时间间隔
main.go ``` package main import ( "fmt" "sync" "time" "github.com/roylee0704/gron" ) func main() { var wg sync.WaitGroup wg.Add(1) c := gron.New() c.AddFunc(gron.Every(5*time.Second), func() { fmt.Println("runs every 5 seconds.") }) c.Start() wg.Wait() } ```

### 按 cron
main.go ``` package main import ( "fmt" "github.com/roylee0704/gron" "github.com/roylee0704/gron/xtime" ) type PrintJob struct{ Msg string } func (p PrintJob) Run() { fmt.Println(p.Msg) } func main() { var ( // schedules daily = gron.Every(1 * xtime.Day) weekly = gron.Every(1 * xtime.Week) monthly = gron.Every(30 * xtime.Day) yearly = gron.Every(365 * xtime.Day) // contrived jobs purgeTask = func() { fmt.Println("purge aged records") } printFoo = printJob{"Foo"} printBar = printJob{"Bar"} ) c := gron.New() c.Add(daily.At("12:30"), printFoo) c.AddFunc(weekly, func() { fmt.Println("Every week") }) c.Start() // Jobs may also be added to a running Gron c.Add(monthly, printBar) c.AddFunc(yearly, purgeTask) // Stop Gron (running jobs are not halted). c.Stop() } ```

';