Executing a function with a timeout

前端 未结 6 736
醉梦人生
醉梦人生 2020-12-14 19:30

What would be an idiomatic way of executing a function within a time limit? Something like,

(with-timeout 5000
 (do-somthing))

Unless do-so

6条回答
  •  Happy的楠姐
    2020-12-14 19:56

    I think you can do this reasonably reliably by using the timeout capability within futures:

      (defmacro with-timeout [millis & body]
        `(let [future# (future ~@body)]
          (try
            (.get future# ~millis java.util.concurrent.TimeUnit/MILLISECONDS)
            (catch java.util.concurrent.TimeoutException x# 
              (do
                (future-cancel future#)
                nil)))))
    

    A bit of experimenting verified that you need to do a future-cancel to stop the future thread from continuing to execute....

提交回复
热议问题