The Startup
Published in

The Startup

Timer Events Instead of Cron Jobs in Go

Timer events in Go

I’ve writing production level Go code for the past 4 years now, something that I’ve been using since the beginning is the timer events in Go.

I use timer events like how I would use cron jobs, to run a function or a script in a certain time interval.

I usually pass the timer interval in a config file to be able to change it quickly without changing the code itself.

I wrote about how I approach configuration in Go projects. You can read more here:

// initVN initializes the refresh timer which will
// refresh all known sites if their version is changed.
func initVN() {
go func() {
every := time.Duration(config.Sites.RefreshEvery) * time.Second
ticker := time.NewTicker(every)
defer ticker.Stop()

for {
select {
case <-ticker.C:
vnSitesRefresh()
}
}
}()
}

// vnSitesRefresh is called every sites refresh timer and
// requests the known sites with versions from VN API.
func vnSitesRefresh() {
logger.Println("Refreshing sites")

// some secret stuff here.
}

The “initVN” function is then called in the init function in the main file, in order to initialize the timer.

package main 

func init() {
pflag.BoolVarP(&versionAsked, "version", "v", false, "Print the version")
pflag.StringVarP(&configPath, "config", "c", "config.toml", "Path to config file")
pflag.Parse()

// Initialize the config.
initConfig()

// Initialize the timer.
initVN()
}

That’s pretty much it. The above code is actually from Violetnorth’s web firewall and is used in production.

If you need to secure your website and your corporate email, you can check out Violetnorth.

Smart web and email firewall to secure your entire infrastructure:

Thanks for stopping by!

--

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

Python Menu

Impose website exercise for beginner frontend developer — “Shopify”

How to speed up a Tree structure traversal in Go?

Basic Tutorials Part 2

Employee Performance Management using Blockchain

IOT experiment part One: Connect to cloud

How to install Spyder without installing anaconda

Switch Statements to the Rescue

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
Koray Göçmen

Koray Göçmen

University of Toronto, Computer Engineering, architected and implemented reliable infrastructures and worked as the lead developer for multiple startups.

More from Medium

Debug your website in production

Coding is Storytelling

How to make a Video Streaming Server with Go — Simplified

TCP and TLS handshake: What happens from typing in a URL to displaying a website? (Part 2)