最近在开发过程中需要定时执行某个函数,因为Golang是常驻内存的,所以在Golang中比较好实现,直接使用第三方库github.com/robfig/cron即可,记录下该库的使用。



安装


github.com/robfig/cron最新版本为3.x,使用下面的命令安装这个库:

go get github.com/robfig/cron/v3@v3.0.0


使用


直接上代码:

package main

import (
	"fmt"
	"time"

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

func main() {
	// 创建一个定时任务的实例,带上cron.WithSeconds()则精确到秒级别
	c := cron.New(cron.WithSeconds())
	// 添加定时任务,每2秒执行一次
	c.AddFunc("*/2 * * * * *", func() {
		fmt.Println("Hello,world!")
	})
	// 添加定时任务,每1秒执行一次,调用test函数
	c.AddFunc("*/1 * * * * *", test)
	// 启动定时任务
	c.Start()
	// 主线程休眠10秒,否则主线程结束,定时任务也会结束
	time.Sleep(10 * time.Second)
}

func test() {
	fmt.Println("每秒执行一次")
}


上面的代码在初始化的时候传递了cron.WithSeconds()作为参数,表示精确到秒级别,则存在6个时间字段,分别为:

秒 分 时 日 月 周


如果不传递cron.WithSeconds()参数,则精确到分钟,存在5个时间字段,分别为:

分 时 日 月 周


可根据自身的业务场景来决定是否需要精确到秒级别。

参考


此文部分内容参考了:

* https://github.com/robfig/cron
* https://pkg.go.dev/github.com/robfig/cron/v3