Last active
March 30, 2021 17:58
-
-
Save ertugrulcetin/437a2547c4c9f764e5ab50617da8366c to your computer and use it in GitHub Desktop.
Ticks scheduler - Clojure core.async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defmacro deftickscheduler [name ticks-per-sec & body] | |
`(when-not *compile-files* | |
(def ~name (let [ticks-per-sec# (/ 1000 ~ticks-per-sec) | |
running?# (volatile! true)] | |
{:var (var ~name) | |
:channel (a/go-loop [] | |
(when @running?# | |
(let [start# (System/currentTimeMillis) | |
_# (do ~@body) | |
elapsed# (- (+ start# ticks-per-sec#) (System/currentTimeMillis))] | |
(when (pos? elapsed#) | |
(a/<! (a/timeout elapsed#))) | |
(recur)))) | |
:running? running?#})))) | |
(defn stop-scheduler [scheduler] | |
(let [{:keys [var channel running?]} scheduler] | |
(vreset! running? false) | |
(a/close! channel) | |
(.unbindRoot var))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment