0
Fork 0
mirror of https://github.com/penpot/penpot.git synced 2025-02-13 02:28:18 -05:00

🎉 Add high level schedule! function to vertx.timers.

This commit is contained in:
Andrey Antukh 2020-01-23 15:47:01 +01:00
parent 685dade614
commit de6fa83e96

View file

@ -14,6 +14,8 @@
io.vertx.core.Vertx
io.vertx.core.Handler))
;; --- Low Level API
(defn schedule-once!
[vsm ms f]
(let [^Vertx system (vu/resolve-system vsm)
@ -33,3 +35,42 @@
java.lang.AutoCloseable
(close [_]
(.cancelTimer system timer-id)))))
;; --- High Level API
(s/def ::once boolean?)
(s/def ::repeat boolean?)
(s/def ::delay integer?)
(s/def ::fn (s/or :fn fn? :var var?))
(s/def ::schedule-opts
(s/keys :req [::fn ::delay] :opt [::once ::repeat]))
(defn schedule!
"High level schedule function."
[vsm {:keys [::once ::repeat ::delay] :as opts}]
(s/assert ::schedule-opts opts)
(when (and (not once) (not repeat))
(throw (IllegalArgumentException. "you should specify `once` or `repeat` params")))
(let [system (vu/resolve-system vsm)
state (atom nil)
taskfn (fn wrapped-task []
(-> (p/do! ((::fn opts) opts))
(p/catch' (constantly nil)) ; explicitly ignore all errors
(p/then' (fn [_] ; the user needs to catch errors
(when repeat
(let [tid (schedule-once! vsm delay wrapped-task)]
(reset! state tid)
nil))))))
tid (schedule-once! vsm delay taskfn)]
(reset! state tid)
(reify
java.lang.AutoCloseable
(close [this]
(locking this
(when-let [timer-id (deref state)]
(.cancelTimer system timer-id)
(reset! state nil)))))))