Implementing Scheduled Tasks in Golang with Cron

golang cronrobfig cron libraryscheduled tasks in gocron job syntaxgo background jobs
Published·Modified·

Recently, during development, I needed to execute a function on a schedule. Since Golang applications run in memory, implementing scheduled tasks is straightforward using the third-party library github.com/robfig/cron. Here is a record of how to use this library.

Installation

The latest version of github.com/robfig/cron is 3.x. Install the library using the following command:

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

Usage

Here is the code:

package main

import (
	"fmt"
	"time"

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

func main() {
	// Create a cron instance. Passing cron.WithSeconds() enables second-level precision
	c := cron.New(cron.WithSeconds())
	// Add a scheduled task to run every 2 seconds
	c.AddFunc("*/2 * * * * *", func() {
		fmt.Println("Hello,world!")
	})
	// Add a scheduled task to run every 1 second, calling the test function
	c.AddFunc("*/1 * * * * *", test)
	// Start the scheduled tasks
	c.Start()
	// Sleep the main thread for 10 seconds; otherwise, the main thread ends and the scheduled tasks stop
	time.Sleep(10 * time.Second)
}

func test() {
	fmt.Println("Executed once per second")
}

In the code above, cron.WithSeconds() is passed during initialization, indicating second-level precision. This results in 6 time fields:

Seconds Minutes Hours Day Month Week

If cron.WithSeconds() is not passed, the precision is down to the minute, resulting in 5 time fields:

Minutes Hours Day Month Week

You can decide whether second-level precision is needed based on your specific business scenario.

References

Parts of this article reference: