Timed loop

A working version is:

function twait(f::Function, timeout::Real=5)
    cond = Condition()
    Timer(x->notify(cond), timeout)
    t = @async begin
        res = f()
        notify(cond)
        res
    end
    wait(cond)
    t.state == :done ? fetch(t) : :timeout
end

If then we have a “heavy” computation, we can do:

heavy(t) = (sleep(t); return t)  # a heavy computation taking t seconds

julia> twait(2) do
           heavy(1)
       end
1

julia> twait(2) do
           heavy(3)
       end
:timeout

In the second case we get a timeout since 2 < 3.

7 Likes