Timer events instead of cron jobs 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 hereHandling configuration in Go
Timer event that runs every certain interval
// 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.
main file
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:Violetnorth
Thanks for stopping by!
Koray Gocmen
Koray Gocmen

University of Toronto, Computer Engineering.

Architected and implemented reliable infrastructures and worked as the lead developer for multiple startups.