Skip to content

Instantly share code, notes, and snippets.

@ertugrulcetin
Last active March 30, 2021 17:58
Show Gist options
  • Save ertugrulcetin/437a2547c4c9f764e5ab50617da8366c to your computer and use it in GitHub Desktop.
Save ertugrulcetin/437a2547c4c9f764e5ab50617da8366c to your computer and use it in GitHub Desktop.
Ticks scheduler - Clojure core.async
(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