定期调用Clojure中的函数 [英] Periodically calling a function in Clojure
问题描述
我正在寻找一种非常简单的方法,在Clojure中定期调用函数。
I'm looking for a very simple way to call a function periodically in Clojure.
JavaScript的 setInterval
有我想要的那种API。如果我在Clojure中重新创建它,它看起来像这样:
JavaScript's setInterval
has the kind of API I'd like. If I reimagined it in Clojure, it'd look something like this:
(def job (set-interval my-callback 1000))
; some time later...
(clear-interval job)
我的目的我不介意,如果这创建一个新的线程,运行在线程池或其他东西。这也不是关键的时机是精确的。事实上,提供的时间(以毫秒为单位)只能是一个调用结束和下一个调用结束之间的延迟。
For my purposes I don't mind if this creates a new thread, runs in a thread pool or something else. It's not critical that the timing is exact either. In fact, the period provided (in milliseconds) can just be a delay between the end of one call completing and the commencement of the next.
推荐答案
Clojure还有很多调度库:
(从简单到非常高级)
There's also quite a few scheduling libraries for Clojure: (from simple to very advanced)
- at-at
- chime (core.async integration)
- monotony
- quartzite
直接从at-at的github主页的示例:
Straight from the examples of the github homepage of at-at:
(use 'overtone.at-at)
(def my-pool (mk-pool))
(let [schedule (every 1000 #(println "I am cool!") my-pool)]
(do stuff while schedule runs)
(stop schedule))
使用(每1000#(printlnI am cool!)my-pool:fixed-delay true)
如果你想在任务结束和开始之间延迟一秒的下一个,而不是两个开始。
Use (every 1000 #(println "I am cool!") my-pool :fixed-delay true)
if you want a delay of a second between end of task and start of next, instead of between two starts.
这篇关于定期调用Clojure中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!