Handle operating system sleep: check regularly the difference between the monotonic clock and the effective time difference

This commit is contained in:
nemunaire 2025-02-18 09:35:43 +01:00
parent b38077c917
commit b7b6d3f0a7

25
app.go
View file

@ -22,6 +22,7 @@ type App struct {
srv *http.Server
nextAlarm *time.Timer
nextPreAlarm *time.Timer
ticker *time.Ticker
}
func NewApp(cfg *config.Config) *App {
@ -61,6 +62,10 @@ func NewApp(cfg *config.Config) *App {
}
func (app *App) Start() {
if app.ticker != nil {
app.ticker.Stop()
}
app.srv = &http.Server{
Addr: app.cfg.Bind,
Handler: app.router,
@ -68,12 +73,28 @@ func (app *App) Start() {
app.ResetTimer()
go app.CheckTime()
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) CheckTime() {
app.ticker = time.NewTicker(time.Minute)
startTime := time.Now()
for range app.ticker.C {
if time.Since(startTime).Round(time.Second).Seconds() != time.Since(startTime.Round(0)).Round(time.Second).Seconds() {
app.ResetTimer()
startTime = time.Now()
}
}
}
func (app *App) ResetTimer() {
if app.nextAlarm != nil {
app.nextAlarm.Stop()
@ -137,6 +158,10 @@ func (app *App) Stop() {
app.nextAlarm.Stop()
}
if app.ticker != nil {
app.ticker.Stop()
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := app.srv.Shutdown(ctx); err != nil {