diff --git a/examples/idle_server_shutdown/main.go b/examples/idle_server_shutdown/main.go new file mode 100644 index 0000000..883f40e --- /dev/null +++ b/examples/idle_server_shutdown/main.go @@ -0,0 +1,35 @@ +package main + +import ( + "context" + "net/http" + "time" + + "go.balki.me/anyhttp/idle" +) + +func main() { + idler := idle.CreateIdler(10 * time.Second) + + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + idler.Tick() + w.Write([]byte("Hey there!\n")) + }) + + http.HandleFunc("/job", func(w http.ResponseWriter, r *http.Request) { + go func() { + idler.Enter() + defer idler.Exit() + + time.Sleep(15 * time.Second) + }() + w.Write([]byte("Job scheduled\n")) + }) + + server := http.Server{ + Addr: ":8888", + } + go server.ListenAndServe() + idler.Wait() + server.Shutdown(context.TODO()) +} diff --git a/idle/idle.go b/idle/idle.go index 4d7825a..5f3d2d7 100644 --- a/idle/idle.go +++ b/idle/idle.go @@ -37,17 +37,16 @@ func CreateIdler(timeout time.Duration) Idler { for { if i.active.Load() != 0 { time.Sleep(timeout) - } else { - t := *i.lastTick.Load() - now := time.Now() - dur := t.Add(timeout).Sub(now) - if dur == dur.Abs() { - time.Sleep(dur) - } else { - break - } + continue } - + t := *i.lastTick.Load() + now := time.Now() + dur := t.Add(timeout).Sub(now) + if dur == dur.Abs() { + time.Sleep(dur) + continue + } + break } close(i.c) }()