使用超时执行函数 [英] Executing a function with a timeout

查看:99
本文介绍了使用超时执行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在时间限制内执行函数的惯用方法是什么?像

 (with-timeout 5000 
(do-somthing))



除非do-something在5000内返回异常或返回nil。



编辑:在某人指出之前,



clojure(with-timeout ... macro)



但是未来会继续执行,在我的情况下无效。

解决方案

这不是你可以100%可靠地在JVM上做的。在一段时间后停止某个事件的唯一方法是给它一个新的线程,然后发送线程异常,当你想要停止。但是他们的代码可以捕获异常,或者他们可以旋转你不能控制的另一个线程,或者...



但是大多数时候,尤其是if您可以控制超时的代码,您可以执行像在clojail



如果你想要更漂亮,你可以定义一个宏

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


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

(with-timeout 5000
 (do-somthing))

Unless do-something returns within 5000 throw an exception or return nil.

EDIT: before someone points it out there is,

clojure (with-timeout ... macro)

but with that the future keeps executing that does not work in my case.

解决方案

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))

这篇关于使用超时执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆