Timer Events Instead of Cron Jobs in Go

Koray Göçmen
2 min readNov 21, 2020
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 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")

// Initialize the config.

// Initialize the timer.

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!



Koray Göçmen

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