How to do repetitive tasks at intervals GO? [SOLVED]


GO

Author: Tuan Nguyen
Reviewer: Deepak Prasad

In today's post, I will introduce to you some ways to do some repetitive tasks at intervals in Golang. We can use the time.Ticker() function or use a channel to complete this purpose.

We developed the functionality of the recurring task to help businesses automate workflows for allocating and overseeing repeated work. There are an endless number of possible uses for this feature, but they all have in common the fact that each new work is automatically generated and added to a list of similar tasks on a regular basis.

 

Method 1: Using the time.NewTicker() function

func NewTicker: NewTicker returns a new Ticker containing a channel that will send the current time on the channel after each tick. The period of the ticks is specified by the duration argument. The ticker will adjust the time interval or drop ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.

In the example below, we will create a ticker with a for loop and iterate it in another goroutine. After 10s, we call Stop() function to turn off the ticker. We also have an interval task that occurs every 2 seconds:

package main

import (
	"fmt"
	"time"
)

func main() {
	ticker := time.NewTicker(2 * time.Second)

	// Creating channel using make
	tickerChan := make(chan bool)

	go func() {
		for {
			select {
			case <-tickerChan:
				return
			// interval task
			case tm := <-ticker.C:
				fmt.Println("The Current time is: ", tm)
				intervalTask()
			}
		}
	}()

	// Calling Sleep() method
	time.Sleep(10 * time.Second)

	// Calling Stop() method
	ticker.Stop()

	// Setting the value of channel
	tickerChan <- true

	// Printed when the ticker is turned off
	fmt.Println("Ticker is turned off!")
}

func intervalTask() {
	fmt.Println("This is interval task")
}

Output:

The Current time is:  2022-12-26 11:35:38.6431689 +0700 +07 m=+2.015583901
This is interval task
The Current time is:  2022-12-26 11:35:40.6330317 +0700 +07 m=+4.005446301
This is interval task
The Current time is:  2022-12-26 11:35:42.6326569 +0700 +07 m=+6.005071101
This is interval task
The Current time is:  2022-12-26 11:35:44.6435402 +0700 +07 m=+8.015954001
This is interval task
Ticker is turned off!

 

Method 2: Using the time.Tick() function

The native range function can be used if you don't care about tick shifting (based on how long it took previously on each execution) and don't want to use channels.

package main

import (
	"fmt"
	"time"
)

func main() {
	go doInterval()
	time.Sleep(time.Second * 10)
}

func doInterval() {
	// each 1 second
	for range time.Tick(time.Second * 1) {
		// do the interval task
		intervalTask()
	}
}

func intervalTask() {
	fmt.Println("This is a interval task")
}

Output:

This is a interval task
This is a interval task
This is a interval task
This is a interval task
This is a interval task
This is a interval task
This is a interval task
This is a interval task
This is a interval task

 

Method 3: Using for loop and time.After function

In the example below, we will create a for loop and run the interval task each 1 second. In the main goroutine, we will stop it after 10 seconds, so the interval task will run 10 times:

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Println("Now:", now)

	after := now.Add(10 * time.Second)
	fmt.Println("After 10 Second:", after)

	for {
		intervalTask()
		// each task occurs every 1 second
		time.Sleep(1 * time.Second)
		now = time.Now()

		// check stop condition
		if now.After(after) {
			break
		}
	}

	fmt.Println("al tasks done")
}

func intervalTask() {
	fmt.Println("This is a interval task!")
}

Output:

Now: 2022-12-26 11:50:42.9987217 +0700 +07 m=+0.001645601
After 10 Second: 2022-12-26 11:50:52.9987217 +0700 +07 m=+10.001645601
This is a interval task!
This is a interval task!
This is a interval task!
This is a interval task!
This is a interval task!
This is a interval task!
This is a interval task!
This is a interval task!
This is a interval task!
This is a interval task!
al tasks done

 

Method 4: Use a third-party library

We can use cron lib to set up the cron job for our program. First of all, you need to install this package by running the following command:

go get github.com/robfig/cron/v3@v3.0.0

Here is an example of using the cron package to schedule our task every minute and every hour:

package main

import (
	"fmt"
	"time"

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

func main() {
	c := cron.New()
	c.AddFunc("0/1 * * * *", func() { fmt.Println("Time now: ", time.Now(), "Every minute") })
	c.AddFunc("@hourly", func() { fmt.Println("Every hour task") })
	c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty task") })
	c.Start()
	time.Sleep(3 * time.Minute)
}

Output:

Time now:  2022-12-26 15:10:00.0126809 +0700 +07 m=+44.122868801 Every minute
Time now:  2022-12-26 15:11:00.0151834 +0700 +07 m=+104.125371301 Every minute
Time now:  2022-12-26 15:12:00.0097011 +0700 +07 m=+164.119889001 Every minute

 

Summary

In this post, I already shared with you some examples of generating repetitive background tasks in Go. We can leverage the built-in package time.NewTicker(), use a native for loop or import a third-party package (cron) to set up the background tasks for our program.

 

References

https://pkg.go.dev/time#Tick
https://github.com/robfig/cron

 

Tuan Nguyen

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment