timetable-mgr/background/ticker.go

74 lines
1.8 KiB
Go

package background
import (
"math"
"os"
"runtime"
"time"
"git.fjla.uk/owlboard/timetable-mgr/cif"
"git.fjla.uk/owlboard/timetable-mgr/corpus"
"git.fjla.uk/owlboard/timetable-mgr/helpers"
"git.fjla.uk/owlboard/timetable-mgr/log"
"git.fjla.uk/owlboard/timetable-mgr/stations"
"go.uber.org/zap"
)
const frequency = 2 * time.Hour // Figure out a sensible frequency!
// Starts a background ticker to run background tasks. Uses the frequency configured in the background/ticker.go file
func InitTicker(cfg *helpers.Configuration, stop <-chan struct{}) {
go runTicker(cfg, stop)
// Run goroutine logging ticker if env "perflog" is set to "on"
if os.Getenv("perflog") == "on" {
go goroutineTicker(stop)
}
}
// Runs the ticker and handles tick events
func runTicker(cfg *helpers.Configuration, stop <-chan struct{}) {
log.Info("Starting background task ticker", zap.Duration("frequency", frequency))
ticker := time.NewTicker(frequency)
defer ticker.Stop()
for {
select {
case <-stop:
log.Debug("Stopping background task ticker")
return
case <-ticker.C:
log.Debug("Running background tasks")
go cif.CheckCif(cfg)
go corpus.CheckCorpus(cfg)
go stations.Check()
}
}
}
// Starts a ticker that logs how many goroutines are running every two seconds
func goroutineTicker(stop <-chan struct{}) {
log.Debug("Starting goroutine resource logging ticker")
ticker := time.NewTicker(1000 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
debugLog()
}
}
}
func debugLog() {
var memStats runtime.MemStats
runtime.ReadMemStats(&memStats)
goroutines := runtime.NumGoroutine()
heapMem := float64(memStats.HeapAlloc) / (1024 * 1024)
heapMemRound := math.Round(heapMem*100) / 100
log.Debug("Performance", zap.Int("goroutine-count", goroutines), zap.Float64("heap-mem (MB)", heapMemRound))
}