Executing code at regularly timed intervals in Clojure

北城以北 提交于 2019-11-29 06:17:40

问题


What's the best way to make code run at regular intervals in Clojure ? I'm currently using java.util.concurrent.ScheduledExecutorService, but that's Java - is there a Clojure way of scheduling code to run at regular intervals, after a delay, cancellably ? All the Clojure code examples I've seen use Thread/sleep, which also seems too Java.


回答1:


Well worth looking at the source code for Overtone, in particular the code for scheduling events at a particular time.

It's a music synthesis system so you have to hope they have the timing code right!!

Also they have helpfully separated the timing code out into a separate project (overtone/at-at) so that you can easily import it if you want. This provides a nice Clojure wrapper to the underlying Java libraries (i.e. ScheduledThreadPoolExecutor and friends). The syntax is like this:

;; run some-function every 500ms
(every 500 some-function)

You can also shedule events at specific times:

;; run some-other-function 10 seconds from now
(at (+ 10000 (now)) some-other-function)



回答2:


From the clojure website http://clojure.org/concurrent_programming:

In all cases, Clojure does not replace the Java thread system, rather it works with it. Clojure functions are java.util.concurrent.Callable, therefore they work with the Executor framework etc.

It sounds like you are already doing it the right way.

(import 'java.util.concurrent.Executors)
(import 'java.util.concurrent.TimeUnit) 
(.scheduleAtFixedRate (Executors/newScheduledThreadPool 1) 
  #(println "Hello") 0 5 TimeUnit/SECONDS)



回答3:


I answered my own question @ Implementing a cron type scheduler in clojure

maybe cronj might help?




回答4:


The "tools.timer" library is a Java Timer wrapper: https://github.com/Ruiyun/tools.timer

It is very easy to use:

(use 'ruiyun.tools.timer)
(run-task! #(println "Say hello every 5 seconds.") :period 5000)


来源:https://stackoverflow.com/questions/8220347/executing-code-at-regularly-timed-intervals-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!