Executing a function with a timeout

前端 未结 6 732
醉梦人生
醉梦人生 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条回答
  •  無奈伤痛
    2020-12-14 19:58

    Adding a possible (macro-less) alternative to the mix (though the macro isn't required in the accepted answer of course)

    (defn with-timeout [f ms]
      (let [p (promise)
            h (future
                (deliver p (f)))
            t (future
                (Thread/sleep ms)
                (future-cancel h)
                (deliver p nil))]
        @p))
    

    Requires two threads, but just an idea.

提交回复
热议问题