diff --git a/src/cif/initialise.go b/src/cif/initialise.go index 8258b04..8d033ad 100644 --- a/src/cif/initialise.go +++ b/src/cif/initialise.go @@ -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) + } } } diff --git a/src/main.go b/src/main.go index c31b1a7..24589aa 100644 --- a/src/main.go +++ b/src/main.go @@ -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) } diff --git a/src/timetable-mgr b/src/timetable-mgr new file mode 100755 index 0000000..910a529 Binary files /dev/null and b/src/timetable-mgr differ