-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.clj
32 lines (29 loc) · 1.07 KB
/
time.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
(ns control-toolbox.time)
(defn fn-throttler-aux-blocking [f rate-ms t-last-run]
(fn [& args]
(let [elapsed (- (System/currentTimeMillis) @t-last-run)
left-to-wait (- rate-ms elapsed)]
(when (pos? left-to-wait)
(Thread/sleep left-to-wait)))
(let [ret (apply f args)]
(reset! t-last-run (System/currentTimeMillis))
ret)))
(defn fn-throttler-aux-non-blocking [f rate-ms t-last-run]
(fn [& args]
(let [now (System/currentTimeMillis)]
(when (>= (- now @t-last-run) rate-ms)
(let [ret (apply f args)]
(reset! t-last-run now)
ret)))))
(defmacro fn-throttler [f rate unit policy]
(let [unit->ms {:millisecond 1
:second 1000
:minute 60000
:hour 3600000
:day 86400000
:month 2678400000}
rate-ms (/ (unit->ms unit) rate)
state '(atom (System/currentTimeMillis))]
(if (= policy :blocking)
`(~'fn-throttler-aux-blocking ~f ~rate-ms ~state)
`(~'fn-throttler-aux-non-blocking ~f ~rate-ms ~state))))