Golang and Cron Jobs: Simplify Your Task Scheduling
What are cron jobs?
Cron jobs also known as time based jobs , are automated processes that perform a certain task at a predefined time interval.Cron jobs are handled by “cron daemon” called crond, which handles the execution of these tasks.
Working of cron job
A cron job is set up in a crontab file, which defines the execution schedule along with other details related to the task.
Crontab Syntax
Creating a cron job in Golang
Among many , the perfect library for creating cron jobs in golang Is the robfig/cron because it closely mimics the functionality and execution style of a traditional crontab, making it both familiar and effective.
In the following sections we will look at how to create a simple cron job that performs a certain task at a given time.
Implementing a cron job in golang
Let us start by creating a new project directory , head to the location and create a new project directory , lets name it go-cron .
Next , open it in a code editor of your choice using the
code .
command.At the moment , the folder is completely empty , let us initialise a go module using the
go mod init <module name>
command that sets up the project.
- The above command creates a go.mod file that sets up the the project dependencies , initially the go.mod file consists of the go version and the name of the module. It looks something like this:
- Next we import the roofing/cron library using the following command.
go get github.com/robfig/cron
After running the above command , your go.mod should look something like this:
We now create a file where all the code goes , the part of the main package . You can name the file anything.
Now , let us write some code!
package main
The package main
declaration is fundamental in Go - it indicates that this is an executable program rather than a library package. This special package name is required for any Go program that's meant to be compiled into an executable and run directly.
import (
"fmt"
"time"
"github.com/robfig/cron/v3"
)
Imports the fmt,time and the robfig/cron packages. fmt is a standard package used for formatting and printing the outputs to the console.
time provides functionality for measuring and displaying time.
github.com/robfig/cron/v3
a third-party package that implements a cron scheduler, allowing you to run tasks on a schedule using cron syntaxThe code starts with
func main()
, which serves as the program's entry point - the first code that executes when you run the application. In Go, every executable program must have exactly one main function in the main package, making it the launching point for all program operations.
location, err := time.LoadLocation("Asia/Kolkata")
if err != nil {
fmt.Println("Error loading the location!")
return
}
c := cron.New(cron.WithLocation(location))
done := make(chan bool)
time package attempts to load the IANA time zone database entry for the Indian time zone. This returns both the location and a potential error using Go's multiple return value feature. The error is checked to ensure the time zone was loaded successfully.
A new cron scheduler instance is created with cron.new(), configured using the functional option pattern via cron.WithLocation(location). This ensures that all scheduled jobs will operate in the specified time zone (Asia/Kolkata), making the scheduling system timezone-aware.
A new go channel is created named ‘done’ which can send and receive boolean values.
_, err = c.AddFunc("21 18 12 1 *", func() {
fmt.Println("Job Ran Successfully!")
done <- true
})
The AddFunc() in the cron package helps in scheduling a job. It takes as arguments the minute, hour,date,month and the day of the week on which the job is to run. In the above given code the job is schedules to run at 6:21 PM on 12th January and is scheduled to run on every day of the week after 12th January. The job specified is simply printing a “Job Run Successfully” message in the console.
Once the job is executed , in the channel done created above we pass the value “true” indicating the job has been executed.
if err != nil {
fmt.Println("Error scheduling job:", err)
return
}
- The above code , basically performs error handling . If the program runs into some error in scheduling the job then the message “Error scheduling job” is printed along with the error that has occurred.
c.Start()
<-done
}
The above line of code calls the Start() of cron library to start the cron job and ←done denotes that the program is waiting to receive a value from the done channel created above.
The final code should look something like this:
package main import ( "fmt" "time" "github.com/robfig/cron/v3" ) func main() { location, err := time.LoadLocation("Asia/Kolkata") if err != nil { fmt.Println("Error loading the location!") return } c := cron.New(cron.WithLocation(location)) done := make(chan bool) _, err = c.AddFunc("21 18 12 1 *", func() { fmt.Println("Job Ran Successfully!") done <- true }) if err != nil { fmt.Println("Error scheduling job:", err) return } c.Start() <-done }
To run the above code , go into the directory where the project is stored and run the following command:
go run <filename>.go
In my case , I named the file main.go . On running the command I get the following output:
- You can find the complete code here. Feel free to explore, clone, or contribute!
Wrapping It Up
I’d love to hear feedback from all the readers. Find me X , Linkedin ! If you found this helpful and would like to support, feel free to Buy me a Coffee!