返回博客

Go 语言 Cron 定时任务详解

本文介绍如何在 Go 语言中使用 robfig/cron 包实现定时任务,包括代码示例和对 V3 版本更新的说明。文章还提供了官方文档和其它参考文章的链接,并讲解了如何处理 V3 版本中新增的秒级定时任务配置。

Mt.r
|

在 go 中使用 cron

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

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

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:

// 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,
)))