Adjust the program cleanup

This commit is contained in:
Fred Boniface 2024-03-25 14:03:19 +00:00
parent d81cade73b
commit e204fb04a4
3 changed files with 30 additions and 14 deletions

View File

@ -8,15 +8,20 @@ import (
// Start a background task to periodically check and update the timetable from the CIF file feed.
func InitBackgroundTask(cfg *helpers.Configuration) {
go runBackgroundTask(cfg)
func InitBackgroundTask(cfg *helpers.Configuration, stop <-chan struct{}) {
go runBackgroundTask(cfg, stop)
}
func runBackgroundTask(cfg *helpers.Configuration) {
func runBackgroundTask(cfg *helpers.Configuration, stop <-chan struct{}) {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
cifCheck(cfg)
for {
select {
case <-stop:
return
case <-ticker.C:
cifCheck(cfg)
}
}
}

View File

@ -5,6 +5,7 @@ import (
"os"
"os/signal"
"syscall"
"time"
"git.fjla.uk/owlboard/timetable-mgr/cif"
"git.fjla.uk/owlboard/timetable-mgr/dbAccess"
@ -28,35 +29,38 @@ func main() {
dbAccess.InitDataAccess(cfg)
dbAccess.PushVersionToDb()
// Handle signals from the OS
go handleSignals(cfg)
// Initialise a `stop` channel to signal goroutines to cleanup
stop := make(chan struct{})
defer cleanup(cfg)
// Handle signals from the OS
go handleSignals(cfg, stop)
// Defer cleanup task
//defer cleanup(cfg, stop)
// Start CIF Task Ticker
cif.InitBackgroundTask(cfg)
cif.InitBackgroundTask(cfg, stop)
if cfg.VstpOn {
messaging.StompInit(cfg)
vstp.Subscribe()
}
select {}
<-stop
}
// Traps SIGINT and SIGTERM signals and ensures cleanup() is run
func handleSignals(cfg *helpers.Configuration) {
func handleSignals(cfg *helpers.Configuration, stop chan<- struct{}) {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigChan
log.Msg.Warn("Signal received: " + sig.String())
cleanup(cfg)
os.Exit(1)
cleanup(cfg, stop)
}
// Cleans up open connections ready for a clean exit of the program
func cleanup(cfg *helpers.Configuration) {
func cleanup(cfg *helpers.Configuration, stop chan<- struct{}) {
log.Msg.Debug("Cleaning up open connections")
if cfg.VstpOn {
if messaging.Client != nil {
@ -68,8 +72,15 @@ func cleanup(cfg *helpers.Configuration) {
log.Msg.Info("Closing MongoDB Client")
dbAccess.CloseMongoClient()
}
log.Msg.Info("Signalling to other goroutines")
close(stop)
log.Msg.Info("Program ready to exit")
if log.Msg != nil {
log.Msg.Sync()
}
time.Sleep(500 * time.Millisecond)
os.Exit(0)
}

BIN
src/timetable-mgr Executable file

Binary file not shown.