Skip to content

Commit

Permalink
backgroundSleep: Use timex.Sleep
Browse files Browse the repository at this point in the history
  • Loading branch information
earthboundkid committed May 2, 2024
1 parent 3fa9d63 commit a64c0cb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
15 changes: 15 additions & 0 deletions internal/timex/timeutil.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package timex

import (
"context"
"sync"
"time"

Expand Down Expand Up @@ -41,3 +42,17 @@ func Equalish(old, new pgtype.Timestamptz) bool {
diff := old.Time.Sub(new.Time).Abs()
return diff < timeWindow
}

// Sleep is like time.Sleep, but it takes a context.
// The return value is false
// if the context cancelled before it could return.
func Sleep(ctx context.Context, d time.Duration) bool {
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
return true
case <-ctx.Done():
return false
}
}
6 changes: 4 additions & 2 deletions pkg/api/routes-background.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/carlmjohnson/flowmatic"
"github.com/spotlightpa/almanack/internal/db"
"github.com/spotlightpa/almanack/internal/paginate"
"github.com/spotlightpa/almanack/internal/timex"
"github.com/spotlightpa/almanack/pkg/almanack"
"github.com/spotlightpa/almanack/pkg/almlog"
)
Expand All @@ -27,10 +28,11 @@ func (app *appEnv) backgroundSleep(w http.ResponseWriter, r *http.Request) http.
if err != nil {
return app.jsonErr(err)
}
time.Sleep(duration)
ok := timex.Sleep(r.Context(), duration)
return app.jsonAccepted(struct {
SleptFor time.Duration `json:"slept-for"`
}{duration})
OK bool `json:"ok"`
}{duration, ok})
}

func (app *appEnv) backgroundCron(w http.ResponseWriter, r *http.Request) http.Handler {
Expand Down

0 comments on commit a64c0cb

Please sign in to comment.