github.com/robfig/cron

安装

github.com/robfig/cron3.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()
秒 分 时 日 月 周
cron.WithSeconds()
分 时 日 月 周

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

参考

此文部分内容参考了: