-
Notifications
You must be signed in to change notification settings - Fork 0
/
impl.clj
178 lines (159 loc) · 5.38 KB
/
impl.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
(ns ivarref.recurring-cup.impl
(:require [tea-time.core :as tt]
[clojure.string :as str]
[clojure.tools.logging :as log])
(:import (java.time ZoneId Instant ZonedDateTime Duration)
(tea_time.core Task)
(java.io Writer)
(clojure.lang IDeref IPending IBlockingDeref)))
(def available-zones
(into (sorted-set) (ZoneId/getAvailableZoneIds)))
(defn ^ZonedDateTime now
([] (now "UTC"))
([tz]
(if (contains? available-zones tz)
(ZonedDateTime/ofInstant
(Instant/ofEpochSecond (tt/unix-time))
(ZoneId/of tz))
(do
(log/error "invalid timezone specified:" tz)
(log/error "must use one of:" (str/join ", " available-zones))
(throw (ex-info "invalid timezone specified" {:timezone tz}))))))
(defn numbers
([] (numbers 0))
([n] (lazy-seq (cons n (numbers (inc n))))))
(defn skip-past [s]
(let [start-from (now)]
(drop-while #(.isBefore % start-from) s)))
(defn- zoned-date-time->linear-micros [^ZonedDateTime zdt]
(tt/unix-micros->linear-micros (tt/seconds->micros (.toEpochSecond zdt))))
(defrecord ZonedDateTimeTask [id f ^long t sq cancelled]
Task
(succ [this] (when-not @cancelled
(when-let [next-time (first sq)]
(assoc this :t (zoned-date-time->linear-micros next-time)
:sq (rest sq)))))
(run [this] (when-not @cancelled
(f)))
(cancel! [this]
(reset! cancelled true)))
(defmethod clojure.core/print-method ZonedDateTimeTask
[task ^Writer writer]
(.write writer "#<ZonedDateTimeTask>")
(.write writer "[")
(.write writer (str/join ", " (mapv str (take 10 (:sq task)))))
(.write writer ", ...]"))
(defonce tasks (atom {}))
(defn schedule!
[id f sq]
(let [cancelled (atom false)
new-task (ZonedDateTimeTask.
(tt/task-id)
(fn []
(let [old-name (.getName (Thread/currentThread))]
(try
(.setName (Thread/currentThread) (str "cup-" (name id)))
(f)
(catch Throwable t
(log/error t "Recurring-cup task" id "threw uncaught exception"))
(finally
(.setName (Thread/currentThread) old-name)))))
(zoned-date-time->linear-micros (first sq))
(rest sq)
cancelled)]
(tt/schedule! new-task)
(swap! tasks update id (fn [old-cancelled]
(when old-cancelled
(reset! old-cancelled true))
cancelled))
new-task))
(defn scheduled-dereffable-job! [id f sq]
(let [p (promise)
a (atom nil)]
(schedule! id
(fn [] (let [r (f)]
(reset! a r)
(deliver p a)))
sq)
(reify
IDeref
(deref [_]
@@p)
IBlockingDeref
(deref [_ timeout-ms timeout-val]
(let [v (deref p timeout-ms timeout-val)]
(if (= v a)
@a
v)))
IPending
(isRealized [_]
(realized? p)))))
(defn dereffable-job!
[id f sq]
; cancel any old job
(swap! tasks update id (fn [old-cancelled]
(when old-cancelled
(reset! old-cancelled true))
nil))
(if @tt/running
(scheduled-dereffable-job! id f sq)
(reify
IDeref
(deref [_]
(f))
IBlockingDeref
(deref [_ _ _]
(f))
IPending
(isRealized [_]
true))))
(defn start! [& {:keys [thread-count park-interval]
:or {thread-count 4
park-interval (Duration/ofMillis 10)}}]
(alter-var-root
(var tt/thread-count)
(constantly thread-count))
(let [park-interval-micros (* (.toMillis park-interval) 1000)]
(alter-var-root
(var tt/park-interval-micros)
(constantly park-interval-micros)))
(tt/start!))
(defn stop! []
(tt/stop!)
(tt/reset-tasks!))
(comment
(do
(println "starting...")
(start!)
(let [begin (-> (now "UTC"))
number->zdt #(-> begin
(.plusSeconds %))
schedule (map number->zdt (numbers))]
(let [job (dereffable-job! ::say-hi
(let [cnt (atom 0)]
(bound-fn []
#_(when (> (Math/random) 0.5))
(throw (ex-info "janei..." {}))
(swap! cnt inc)))
(skip-past schedule))]
(def j job)))))
(comment
(do
(println "starting...")
(start!)
(let [begin (-> (now "UTC"))
number->zdt #(-> begin
(.plusSeconds %))
schedule (map number->zdt (numbers))]
(schedule! ::say-hi
(let [cnt (atom 0)]
(bound-fn []
(println "hello" (swap! cnt inc))
#_(Thread/sleep 10000)))
(skip-past schedule))
#_(Thread/sleep 3000)
#_(schedule! ::say-hi
(let [cnt (atom 0)]
(bound-fn []
(println "hi" (.getName (Thread/currentThread)) (swap! cnt inc))))
(skip-past schedule)))))