Executing a function with a timeout

前端 未结 6 748
醉梦人生
醉梦人生 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:53

    This isn't something you can do 100% reliably on the JVM. The only way to stop something after a while is to give it a new thread, and then send that thread an exception when you want it to stop. But their code can catch the exception, or they can spin up another thread that you don't control, or...

    But most of the time, and especially if you control the code that's being timed out, you can do something like we do in clojail:

    If you wanted to make that prettier you could define a macro like

    (defmacro with-timeout [time & body]
      `(thunk-timeout (fn [] ~@body) ~time))
    

提交回复
热议问题