Using Goroutines to run a poor mans Cron Job
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 canclose()
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
byselect
combo, which allows you to wait on multiple channel operations repeatedly.ticker.C
gives us achan
oftime.Time
quit
gives us achan
ofbool
- Using these two, we can invoke
report()
gracefully.
Sidenotes
- Don't forget to utilise the returning
chan bool
when you're callingStart()
to gracefully shut down the ticker.