Help writing a timeout macro

I’ll just leave my approach here…

macro timeout(expr, seconds=-1, cb=(tsk) -> Base.throwto(tsk, InterruptException()))
    quote
        tsk = @task $expr
        schedule(tsk)

        if $seconds > -1
            Timer((timer) -> $cb(tsk), $seconds)
        end

        return fetch(tsk)
    end
end

julia> @timeout (sleep(3); println("done")) 3.1
done

julia> @timeout (sleep(3); println("done")) 3
ERROR: TaskFailedException:
InterruptException:
Stacktrace:
 [1] try_yieldto(::typeof(Base.ensure_rescheduled)) at ./task.jl:656
 [2] wait at ./task.jl:713 [inlined]
 [3] wait(::Base.GenericCondition{Base.Threads.SpinLock}) at ./condition.jl:106
 [4] _trywait(::Timer) at ./asyncevent.jl:110
 [5] wait at ./asyncevent.jl:128 [inlined]
 [6] sleep at ./asyncevent.jl:213 [inlined]
 [7] (::var"#29#31")() at ./task.jl:112
Stacktrace:
 [1] wait at ./task.jl:267 [inlined]
 [2] fetch(::Task) at ./task.jl:282
 [3] top-level scope at REPL[3]:10
2 Likes