执行带有超时的函数 [英] Executing a function with a timeout

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

问题描述

在时间限制内执行功能的惯用方式是什么?类似的东西,

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

(with-timeout 5000
 (do-somthing))

除非 do-something 在 5000 内返回,否则抛出异常或返回 nil.

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

在有人指出之前,

clojure(带超时...宏)

但是随着未来的继续执行,在我的情况下不起作用.

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

推荐答案

这不是您可以 100% 可靠地在 JVM 上完成的事情.一段时间后停止某事的唯一方法是给它一个新线程,然后在您希望它停止时向该线程发送一个异常.但是他们的代码可以捕获异常,或者他们可以启动另一个您无法控制的线程,或者...

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

但大多数时候,特别是如果你控制超时的代码,你可以像我们做的那样在 clojail 中:

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天全站免登陆