Running periodic background tasks in Golang

Image for post
Image for post

The Problem —

Run tasks periodically —

But wait, What is Cron?

Image for post
Image for post
package main

import (

func myTask() {
fmt.Println("This task will run periodically")
func executeCronJob() {
<- gocron.Start()
func main() {
go executeCronJob()
SomeAPICallHandler() // handler which accepts requests and responds
gocron.Every(1).Minute().Do(myTask) // Every Minute
gocron.Every(2).Hours().Do(myTask) // Every 2 Hours
gocron.Every(3).Days().Do(myTask) // Every 3 Days
gocron.Every(4).Weeks().Do(myTask) // Every 4 Weeks

Run tasks in the background -

go executeCronJob()

Catch in above code

time.Sleep(500 * time.Millisecond)

Keep exploring, keep learning!

Product Engineer @ gojek |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store