timetable-mgr/background/ticker.go
Fred Boniface f243fc6831
All checks were successful
Go Test / test (push) Successful in 1m49s
Add debug heap memory allocation
2024-04-08 21:39:52 +01:00

67 lines
1.6 KiB
Go

package background
import (
"fmt"
"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"
)
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.Msg.Sugar().Infof("Starting background ticker, runs every %s", 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.Msg.Warn("Starting goroutine Tracker ticker - DEBUG USE ONLY")
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()
fmt.Printf("\nNumber of goroutines: %d\n", goroutines)
fmt.Printf("Heap Allocated memory: %2f MB\n\n", float64(memStats.HeapAlloc)/(1024*1024))
}