-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.clj
51 lines (39 loc) · 1.34 KB
/
core.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
(ns mem-files.core
(:require [clojure.java.io :as io])
(:import (java.lang AutoCloseable)
(clojure.lang IDeref)))
(defn- slurp-if-exists [file]
(when (.exists (io/as-file file))
(slurp file)))
(defn- load-one [*cache k file parse-fn]
;; If the file is missing or parse-fn throws, will put nil
(let [new-value (try (some-> (slurp-if-exists file)
parse-fn)
(catch Exception _))]
(swap! *cache assoc k new-value)))
(defn- load-all [*cache keys-files parse-fn]
(doseq [[k f] keys-files]
(load-one *cache k f parse-fn)))
(defn- worker [f interval-ms]
(loop []
(when-not (= ::stop
(try
(Thread/sleep interval-ms)
(f)
(catch InterruptedException e
::stop)
(catch Exception e)))
(recur))))
(deftype MemFiles [*cache thread]
IDeref
(deref [_] @*cache)
AutoCloseable
(close [_] (.interrupt thread)))
(defn start
([interval-ms keys-files]
(start interval-ms keys-files identity))
([interval-ms keys-files parse-fn]
(let [*cache (atom {})
_ (load-all *cache keys-files parse-fn)
thread (doto (Thread. (fn [] (worker #(load-all *cache keys-files parse-fn) interval-ms))) .start)]
(MemFiles. *cache thread))))