clojure(with-timeout ...宏) [英] clojure (with-timeout ... macro)
本文介绍了clojure(with-timeout ...宏)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一个宏,如果表达式需要超过X秒完成,它会抛出异常。
I'm looking for a macro that will throw an exception if an expression takes longer than X seconds to complete.
推荐答案
这个问题有更好的答案:
执行超时功能
This question has better answers here: Executing a function with a timeout
期待救援!
user=> (let [f (future (reduce * (range 1 1001)))]
(.get f 1 java.util.concurrent.TimeUnit/MILLISECONDS))
java.util.concurrent.TimeoutException (NO_SOURCE_FILE:0)
并创建一个宏:
(defmacro time-limited [ms & body]
`(let [f# (future ~@body)]
(.get f# ~ms java.util.concurrent.TimeUnit/MILLISECONDS)))
p>
So you can do this:
user=> (time-limited 1 (reduce * (range 1 1001)))
java.util.concurrent.TimeoutException (NO_SOURCE_FILE:0)
user=> (time-limited 1 (reduce * (range 1 101)))
93326215443944152681699238856266700490715968264381621468592963895217599993229915
608941463976156518286253697920827223758251185210916864000000000000000000000000
这篇关于clojure(with-timeout ...宏)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!