Building a simple CRON in Go with GoCron
Last edited on November 14, 2024Introduction
Traditionally a cron is a job scheduler that allows the user to run "jobs" at specifically timed intervals. The most common application for creating cron-Jobs is scheduling repetitive tasks. In this post we'll go over setting up a simple cron using the go-co-op/gocron/v2 package and log a message to our terminal. This sets up the ground work for adding actual jobsinto the chronological sequence later down the line.
Setup
First things first let's set up our new project.
$ mkdir examplecron && cd examplecron
Now that we have a project directory, create a main.go file in the root of that directory so we have a place to write our code.
As a personal preference, I create my main.go and then follow it with initializing go-mod
$ touch main.go && go mod init
After creating a main.go we need to install a reference to the gocron package to be able to use it in our project.
$ go get github.com/go-co-op/gocron
Write It
Now that we have the dependency let's pull in gocron and create a function that starts a new job on a set interval.
package main
import (
"fmt"
"time"
"github.com/go-co-op/gocron"
)
func main() {
s, err := gocron.NewScheduler(time.UTC)
if err != nil {
// handle error
}
job, err := s.NewJob(
gocron.DurationJob(
5*time.Second,
),
gocron.NewTask(
func() {
fmt.Println("Hey, we're cronning!")
}
)
)
if err != nil {
// handle error
}
s.StartBlocking()
}
Running this code starts a new scheduler in the UTC timezone. It will run a task every 5 seconds that prints out a line. This is a blocking function that will halt the main thread on execution until signaled to shut down (CTRL|CMD+C).
If we were to run the code we would see
$ go run main.go
>> Hey, we're cronning!
>> Hey, we're cronning!
>> Hey, we're cronning!
Summary
We have successfully created and scheduled a cron job using Go and the gocron library! There are a handful other libraries to take into consideration, but this one has worked for me in many cases. Thanks for reading!