package background import ( "math" "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" "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 runtime set to debug if helpers.Runtime == "debug" { 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: return case <-ticker.C: go cif.CheckCif(cfg) go corpus.CheckCorpus(cfg) } } } // 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)) }