# Help writing a timeout macro

**URL:** https://discourse.julialang.org/t/help-writing-a-timeout-macro/16591
**Category:** General Usage
**Tags:** macros, task
**Created:** [October 21, 2018, 3:47am UTC](https://discourse.julialang.org/t/help-writing-a-timeout-macro/16591 "2018-10-21T03:47:37Z")
**Posts on this page:** 1
**Showing post:** 5

<div class="post-metadata">

### Author: ![captchanjack](https://avatars.discourse-cdn.com/v4/letter/c/74df32/32.png) [@captchanjack](https://discourse.julialang.org/u/captchanjack)
#### Post date: [June 7, 2021, 5:09pm UTC](https://discourse.julialang.org/t/help-writing-a-timeout-macro/16591/5 "2021-06-07T17:09:00Z")

</div>

I’ll just leave my approach here…

```julia
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

```

---

_[View the full topic](https://discourse.julialang.org/t/help-writing-a-timeout-macro/16591)._
