golang

Golang Cron

Crontab or Cron for short is an extremely useful utility found in Unix-Like operating systems. It allows you to schedule commands or tasks to run at a specific time. Typically, cron is very useful when performing repetitive tasks such as backups, deleting files, collecting logs, automated system maintenance, and more.

A scheduled task, also known as a cron job uses very time formats to determine when to run. For example, you can create a simple cronjob that runs when the system reboots.

To learn more on how to use the Crontab utility, check this tutorial. In this guide, however, we will discuss how we can implement cron tasks using the Go language.

Golang Cron Package

To create and run cron tasks using Golang, we need to install and import the Go cron package.

Start by creating a working directory to store your Golang code.

mkdir crons

cd crons

Next, run the command below to install the package:

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

Once installed, create a Go file to store your code

touch main.go

Open the main.go file with your text editor and import the package using the line shown below:

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

Golang Create Cron Object

The first step is to create a cron object using the cron.New() method. You can then use this object manage and schedule tasks.

cron := cron.New()

The above should return a new cron job runner with the defined time zone. If no time zone is specified, the function will use the local time zone.

Golang Add Func

The next step is to call the AddFunc method on the cron object. This allows us to add a time to the job manager. The function syntax is as shown:

func (c *Cron) AddFunc(spec string, cmd func()) error

It takes the duration under which the specified function will run. You can set this value to any time.ParseDuration() format. For example, to set a function to run every minute, we can specify the parameter as: @every 1m.

The second parameter is the function which to execute.

An example code is as shown below:

package main
import (
    "fmt"

    "github.com/robfig/cron/v3"
)
funcmain() {
    cron := cron.New()
    cron.AddFunc("@every 1m", func ()  {
        fmt.Println("Hi Every minute!")
    })
}

In this example, we define a function that prints “Hi Every minute”, every minute.

The next step is to start the cron scheduler. For this, we can use the cron.Start() method. The function will take the scheduler and run it in its own go-routine.

cron.Start()

time.Sleep(time.Minute * 5)

The above code starts the cron scheduler using the Start() method. We also include the time.Sleep() method with a parameter of 5 minutes. This is because the Start() methods runs in its own go-routine for loop detection. The sleep method prevents the go routine from exiting.

If we run the above code, we should get an output as:

$ go run main.go

Hi Every Minute!

Hi Every Minute!

Hi Every Minute!

.

Golang Expression Formats

You can use various expression formats to define a set of times and durations under which a task will run.

The cron package supports the following expressions:

  1. An asterisk shows the expression matches all the values of the field.
  2. A forward slash describes the increment of ranges.
  3. Comma separates a list of items.
  4. Hyphen defines a set of ranges.

You can also use the pre-defined formats as shown:

Closing

This was an introductory tutorial on creating and scheduling tasks using cron in the Go language. Check the docs for more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list