Stipple.jl
Stipple.jl copied to clipboard
Macro to timeout operations that take too long
Hi!
On my Genie app, there are some cases where, if the user inputs unphysical conditions, the solvers will get stuck / take a long time to output an unreasonable result. As such, it would be great to have some sort of macro that will only allow a task to only run for a certain amount of time. There was an example here: https://discourse.julialang.org/t/simple-timeout-of-function/99578/3
The macro they propose looks like this:
macro timeout(seconds, expr_to_run, expr_when_fails="Timed out")
quote
tsk = @task $(esc(expr_to_run))
schedule(tsk)
Timer($(esc(seconds))) do timer
istaskdone(tsk) || Base.throwto(tsk, InterruptException())
end
try
fetch(tsk)
catch _
$(esc(expr_when_fails))
end
end
end
However, I've found that this macro doesn't work for my cases. Here is an MWE (you'll need to install Clapeyron):
using Clapeyron
model = PCSAFT(["water", "carbon dioxide"])
@time bubble_pressure(model,298.15,[0.9,0.1])
# After first compilation, this should take about 0.8s
@timeout 0.01 bubble_pressure(model,298.15,[0.9,0.1])
# Doesn't timeout