Add example for idle
This commit is contained in:
parent
710e8b66e6
commit
ea04fe735b
35
examples/idle_server_shutdown/main.go
Normal file
35
examples/idle_server_shutdown/main.go
Normal file
@ -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())
|
||||
}
|
19
idle/idle.go
19
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)
|
||||
}()
|
||||
|
Loading…
Reference in New Issue
Block a user