Event on next alarm reached

This commit is contained in:
nemunaire 2022-10-06 14:17:58 +02:00
commit fffdccc7b8
3 changed files with 56 additions and 16 deletions

52
app.go
View file

@ -15,13 +15,14 @@ import (
)
type App struct {
cfg *config.Config
db *reveil.LevelDBStorage
router *gin.Engine
srv *http.Server
cfg *config.Config
db *reveil.LevelDBStorage
router *gin.Engine
srv *http.Server
nextAlarm *time.Timer
}
func NewApp(cfg *config.Config) App {
func NewApp(cfg *config.Config) *App {
if cfg.DevProxy == "" {
gin.SetMode(gin.ReleaseMode)
}
@ -38,21 +39,21 @@ func NewApp(cfg *config.Config) App {
log.Fatal("Unable to open the database:", err)
}
// Register routes
ui.DeclareRoutes(router, cfg)
api.DeclareRoutes(router, cfg, db)
router.GET("/api/version", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"version": Version})
})
// We are ready!
app := App{
// Prepare struct
app := &App{
cfg: cfg,
db: db,
router: router,
}
// Register routes
ui.DeclareRoutes(router, cfg)
api.DeclareRoutes(router, cfg, db, app.ResetTimer)
router.GET("/api/version", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"version": Version})
})
return app
}
@ -62,13 +63,34 @@ func (app *App) Start() {
Handler: app.router,
}
app.ResetTimer()
log.Printf("Ready, listening on %s\n", app.cfg.Bind)
if err := app.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}
func (app *App) ResetTimer() {
if app.nextAlarm != nil {
app.nextAlarm.Stop()
app.nextAlarm = nil
}
if na, err := reveil.GetNextAlarm(app.db); err == nil && na != nil {
app.nextAlarm = time.AfterFunc(time.Until(*na), func() {
app.nextAlarm = nil
log.Println("RUN WAKEUP FUNC")
})
log.Println("Next timer programmed for", *na)
}
}
func (app *App) Stop() {
if app.nextAlarm != nil {
app.nextAlarm.Stop()
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := app.srv.Shutdown(ctx); err != nil {