-
Notifications
You must be signed in to change notification settings - Fork 14
/
cleaner.clj
42 lines (37 loc) · 1.49 KB
/
cleaner.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
(ns jdbc-ring-session.cleaner
(:require [next.jdbc.sql :as jdbc.sql]
[next.jdbc :as jdbc])
(:import [java.util.concurrent Executors TimeUnit ScheduledExecutorService]))
(defn remove-sessions
"removes stale sessions from the session table"
[datasource {:keys [table]
:or {table :session_store}}]
(let [t (quot (System/currentTimeMillis) 1000)]
(jdbc/with-transaction [tx datasource]
(jdbc.sql/delete! tx table ["idle_timeout < ? or absolute_timeout < ?" t t]))))
(defprotocol Stoppable
"Something that can be stopped"
(stopped? [_] "Return true if stopped, false otherwise")
(stop [_] "Stop (idempotent)"))
(defn start-cleaner
"starts a session cleaner
conn - database connection
config - configuration map that ring-jdbc-session was initialized with"
([conn] (start-cleaner conn {}))
([conn {:keys [interval]
:or {interval 60}
:as config}]
(let [scheduler ^ScheduledExecutorService (Executors/newScheduledThreadPool 1)]
(.scheduleWithFixedDelay scheduler
(fn [] (remove-sessions conn config))
0
(long interval)
TimeUnit/SECONDS)
(reify Stoppable
(stopped? [_] (.isShutdown scheduler))
(stop [_] (.shutdown scheduler))))))
(defn stop-cleaner
"stops the instance of the session cleaner"
[session-cleaner]
{:pre [(satisfies? Stoppable session-cleaner)]}
(.stop session-cleaner))