aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorShulhan <m.shulhan@gmail.com>2020-04-01 08:19:20 +0700
committerShulhan <m.shulhan@gmail.com>2020-04-01 08:19:20 +0700
commit3061f6561c746f216586c271a10219515dcdb2d7 (patch)
tree9272ea3e54f579463ded0ab6caee4a5acce8d421
parent9613122cf6b0f315b6071704b60ab902906362b1 (diff)
downloadkamusku-3061f6561c746f216586c271a10219515dcdb2d7.tar.xz
server: dump the cache when server shutting down
-rw-r--r--cmd/www-kbbi/main.go2
-rw-r--r--server.go55
2 files changed, 47 insertions, 10 deletions
diff --git a/cmd/www-kbbi/main.go b/cmd/www-kbbi/main.go
index bb4cd86..7a959d5 100644
--- a/cmd/www-kbbi/main.go
+++ b/cmd/www-kbbi/main.go
@@ -28,4 +28,6 @@ func main() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
+
+ server.Shutdown()
}
diff --git a/server.go b/server.go
index a241f05..ec4aedd 100644
--- a/server.go
+++ b/server.go
@@ -9,6 +9,7 @@ import (
"log"
stdhttp "net/http"
"strings"
+ "sync"
"time"
"github.com/shuLhan/share/lib/http"
@@ -32,6 +33,9 @@ type Server struct {
// If offline is true and the word definition is not found on cache,
// the server will not forward request to official KBBI server.
offline bool
+
+ wg sync.WaitGroup
+ stopped chan bool
}
//
@@ -42,7 +46,9 @@ func NewServer() (server *Server, err error) {
Address: defListen,
}
- server = &Server{}
+ server = &Server{
+ stopped: make(chan bool, 1),
+ }
server.kamus, err = newKamusCache("")
if err != nil {
@@ -72,27 +78,56 @@ func NewServer() (server *Server, err error) {
//
func (server *Server) Start() (err error) {
go server.dumpCache()
+ server.wg.Add(1)
return server.http.Start()
}
//
-// dumpCache periodically dump the cache to file to be loaded later.
+// Shutdown the HTTP server and save the cache for future use.
//
-func (server *Server) dumpCache() {
+func (server *Server) Shutdown() (err error) {
+ err = server.Shutdown()
+
+ server.stopped <- true
+
+ // Wait for all jobs to be completed.
+ server.wg.Wait()
+
+ return err
+}
+
+//
+// dumpCacheJob periodically save the cache or when the server stopped.
+//
+func (server *Server) dumpCacheJob() {
ticker := time.NewTicker(1 * time.Hour)
- for range ticker.C {
- if !server.kamus.isChanging() {
- continue
- }
- err := server.kamus.store()
- if err != nil {
- log.Println("server.dumpCache: ", err)
+ for {
+ select {
+ case <-ticker.C:
+ server.dumpCache()
+ case <-server.stopped:
+ server.dumpCache()
+ server.wg.Done()
+ return
}
}
}
+//
+// dumpCache to storage to be loaded later.
+//
+func (server *Server) dumpCache() {
+ if !server.kamus.isChanging() {
+ return
+ }
+ err := server.kamus.store()
+ if err != nil {
+ log.Println("server.dumpCache: ", err)
+ }
+}
+
func (server *Server) handleDefinisi(
httpRes stdhttp.ResponseWriter,
httpReq *stdhttp.Request,