Handle operating system sleep: check regularly the difference between the monotonic clock and the effective time difference
This commit is contained in:
parent
b38077c917
commit
b7b6d3f0a7
1 changed files with 25 additions and 0 deletions
25
app.go
25
app.go
|
|
@ -22,6 +22,7 @@ type App struct {
|
||||||
srv *http.Server
|
srv *http.Server
|
||||||
nextAlarm *time.Timer
|
nextAlarm *time.Timer
|
||||||
nextPreAlarm *time.Timer
|
nextPreAlarm *time.Timer
|
||||||
|
ticker *time.Ticker
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewApp(cfg *config.Config) *App {
|
func NewApp(cfg *config.Config) *App {
|
||||||
|
|
@ -61,6 +62,10 @@ func NewApp(cfg *config.Config) *App {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) Start() {
|
func (app *App) Start() {
|
||||||
|
if app.ticker != nil {
|
||||||
|
app.ticker.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
app.srv = &http.Server{
|
app.srv = &http.Server{
|
||||||
Addr: app.cfg.Bind,
|
Addr: app.cfg.Bind,
|
||||||
Handler: app.router,
|
Handler: app.router,
|
||||||
|
|
@ -68,12 +73,28 @@ func (app *App) Start() {
|
||||||
|
|
||||||
app.ResetTimer()
|
app.ResetTimer()
|
||||||
|
|
||||||
|
go app.CheckTime()
|
||||||
|
|
||||||
log.Printf("Ready, listening on %s\n", app.cfg.Bind)
|
log.Printf("Ready, listening on %s\n", app.cfg.Bind)
|
||||||
if err := app.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
if err := app.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
log.Fatalf("listen: %s\n", err)
|
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() {
|
func (app *App) ResetTimer() {
|
||||||
if app.nextAlarm != nil {
|
if app.nextAlarm != nil {
|
||||||
app.nextAlarm.Stop()
|
app.nextAlarm.Stop()
|
||||||
|
|
@ -137,6 +158,10 @@ func (app *App) Stop() {
|
||||||
app.nextAlarm.Stop()
|
app.nextAlarm.Stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if app.ticker != nil {
|
||||||
|
app.ticker.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if err := app.srv.Shutdown(ctx); err != nil {
|
if err := app.srv.Shutdown(ctx); err != nil {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue