Go语言学习: Cron jobs 定时任务

在 go 语言里实现定时任务的基本代码
更新于: 2024-10-18 07:05:23

安装

go get github.com/robfig/cron

基本使用

package main

import (
    "fmt"
    "time"

    "github.com/robfig/cron"
)

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

    // Define the Cron job schedule(间隔5秒,运行一次)
    c.AddFunc("*/5 * * * *", func() {
        fmt.Println("Hello world!")
    })

    // Start the Cron job scheduler
    c.Start()

    // Wait for the Cron job to run(等2分钟,停止)
    time.Sleep(2 * time.Minute)

    // Stop the Cron job scheduler
    c.Stop()
}

预定义时间规则

为了方便使用,cron预定义了一些时间规则:

  • @yearly:也可以写作@annually,表示每年第一天的 0 点。等价于0 0 1 1 *
  • @monthly:表示每月第一天的 0 点。等价于0 0 1 * *
  • @weekly:表示每周第一天的 0 点,注意第一天为周日,即周六结束,周日开始的那个 0 点。等价于0 0 * * 0
  • @daily:也可以写作@midnight,表示每天 0 点。等价于0 0 * * *
  • @hourly:表示每小时的开始。等价于0 * * * *