计算有时间限制 [英] Computation with time limit
问题描述
我正在尝试编写一个允许我在给定时间窗口中运行计算的构造。类似于:
I'm trying to write a construct which allows me to run computations in a given time window. Something like:
def expensiveComputation(): Double = //... some intensive math
val result: Option[Double] = timeLimited( 45 ) { expensiveComputation() }
这里 timeLimited
将运行 expensiveComputation
,超时为45分钟。如果达到超时,它返回无
,否则它将结果包装到一些
。
Here the timeLimited
will run expensiveComputation
with a timeout of 45 minutes. If it reaches the timeout it returns None
, else it wrapped the result into Some
.
我正在寻找一个解决方案:
I am looking for a solution which:
- 性能和内存相当便宜;
-
将在当前主题中运行限时任务。
- Is pretty cheap in performance and memory;
Will run the time-limited task in the current thread.
有任何建议吗?
编辑
我理解我的原始问题没有解决方案。假设我可以为计算创建一个线程(但我不想使用线程池/执行器/调度程序)。什么是最快,最安全,最干净的方法?
I understand my original problem has no solution. Say I can create a thread for the calculation (but I prefer not using a threadpool/executor/dispatcher). What's the fastest, safest and cleanest way to do it ?
推荐答案
运行给定的代码块或在超时时抛出异常:
Runs the given code block or throws an exception on timeout:
@throws(classOf[java.util.concurrent.TimeoutException])
def timedRun[F](timeout: Long)(f: => F): F = {
import java.util.concurrent.{Callable, FutureTask, TimeUnit}
val task = new FutureTask(new Callable[F]() {
def call() = f
})
new Thread(task).start()
task.get(timeout, TimeUnit.MILLISECONDS)
}
这篇关于计算有时间限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!