How to Schedule Cron Jobs in Golang

This golang tutorial help to create schedule a jon to execute at specific time interval


This golang tutorial help to create schedule a jon to execute at specific time interval.This is very helpful feature to run a process or tasks as background, that can be a job that pull data from third party server, sync data between two server, send an email notification at a specific inerval.

Getting started

To get the package, execute:
go get gopkg.in/robfig/cron.v2
To import this package, add the following line to your code:
import "gopkg.in/robfig/cron.v2"

Usage

Callers may register Funcs to be invoked on a given schedule. Cron will run them in their own goroutines.

CRON Expression Format
A cron expression represents a set of times, using 6 space-separated fields.
Field name Mandatory? Allowed values Allowed special characters ---------- ---------- -------------- -------------------------- Seconds No 0-59 * / , - Minutes Yes 0-59 * / , - Hours Yes 0-23 * / , - Day of month Yes 1-31 * / , - L W Month Yes 1-12 or JAN-DEC * / , - Day of week Yes 0-6 or SUN-SAT * / , - L # Year No 1970–2099 * / , -
Note: Month and Day-of-week field values are case insensitive. "SUN", "Sun", and "sun" are equally accepted.

Predefined schedules

You may use one of several pre-defined schedules in place of a cron expression.
Entry Description Equivalent to @annually Run once a year at midnight in the morning of January 1 0 0 0 1 1 * * @yearly Run once a year at midnight in the morning of January 1 0 0 0 1 1 * * @monthly Run once a month at midnight in the morning of the first of the month 0 0 0 1 * * * @weekly Run once a week at midnight in the morning of Sunday 0 0 0 * * 0 * @daily Run once a day at midnight 0 0 0 * * * * @hourly Run once an hour at the beginning of the hour 0 0 * * * * *


Intervals

You may also schedule a job to execute at fixed intervals. This is supported by formatting the cron spec like this:
@every <duration>
where "duration" is a string accepted by time.ParseDuration (http://golang.org/pkg/time/#ParseDuration). For example, "@every 1h30m10s" would indicate a schedule that activates every 1 hour, 30 minutes, 10 seconds.
Note: The interval does not take the job runtime into account. For example, if a job takes 3 minutes to run, and it is scheduled to run every 5 minutes, it will have only 2 minutes of idle time between each run.
Gopher

Feb 20 2020

Write your response...

On a mission to build Next-Gen Community Platform for Developers