Using cron for scheduling tasks in Golang

Publish: 2023-02-01 | Modify: 2023-02-01

Recently, I needed to execute a certain function at regular intervals during the development process. Since Golang is memory-resident, it is relatively easy to implement in Golang by using the third-party library github.com/robfig/cron. Let me record how to use this library.

Installation

The latest version of github.com/robfig/cron is 3.x. Use the following command to install this library:

go get github.com/robfig/cron/[email protected]

Usage

Let's dive into the code:

package main

import (
    "fmt"
    "time"

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

func main() {
    // Create an instance of cron job, use cron.WithSeconds() for second-level precision
    c := cron.New(cron.WithSeconds())
    // Add a cron job, execute every 2 seconds
    c.AddFunc("*/2 * * * * *", func() {
        fmt.Println("Hello, world!")
    })
    // Add a cron job, execute every 1 second, call the test function
    c.AddFunc("*/1 * * * * *", test)
    // Start the cron job
    c.Start()
    // Sleep the main thread for 10 seconds, otherwise the cron job will end when the main thread ends
    time.Sleep(10 * time.Second)
}

func test() {
    fmt.Println("Execute every second")
}

In the above code, we passed cron.WithSeconds() as a parameter during initialization, indicating second-level precision, which means there are 6 time fields:

second minute hour day month week

If you don't pass the cron.WithSeconds() parameter, it will be minute-level precision, which means there are 5 time fields:

minute hour day month week

You can decide whether to use second-level precision based on your own business scenario.

Reference

Some of the content in this article is referenced from:


Comments