⏲️

Using Goroutines to run a poor mans Cron Job

Created
Nov 2, 2021 8:16 PM
Tags
computinggolangobservability

Lately, I wanted to push some stuff to a statsD server from within a golang application, without setting up a whole new init for a cron job.

Turns out, it's pretty easy when you're using goroutines to get that working.

func Start() chan bool {
	ticker := time.NewTicker(10 * time.Minute)
	quit := make(chan bool, 1)

	go func() {
		for {
			select {
			case <-ticker.C:
				report()
			case <-quit:
				ticker.Stop()
			}
		}
	}()

	return quit
}

func report() {
	// do your thing here
}

Explanation

  • You'd initiate a Ticker first. Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals - GoByExample.
  • You'd make a channel chan, that you can close() later on. This will help us stop the ticker gracefully when the main thread stops.
  • Initiate your goroutine, as you'd do normally with go func()
  • Use the for by select combo, which allows you to wait on multiple channel operations repeatedly.
    • ticker.C gives us a chan of time.Time
    • quit gives us a chan of bool
    • Using these two, we can invoke report() gracefully.

Sidenotes

  • Don't forget to utilise the returning chan bool when you're calling Start() to gracefully shut down the ticker.