# A cancellable async loop?

**URL:** <https://discourse.julialang.org/t/a-cancellable-async-loop/57068>\
**Category:** New to Julia\
**Created:** [March 13, 2021, 11:48am UTC](https://discourse.julialang.org/t/a-cancellable-async-loop/57068 "2021-03-13T11:48:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![danvenn](https://avatars.discourse-cdn.com/v4/letter/d/46a35a/32.png) [@danvenn](https://discourse.julialang.org/u/danvenn)\
**Post date:** [March 13, 2021, 11:48am UTC](https://discourse.julialang.org/t/a-cancellable-async-loop/57068/1 "2021-03-13T11:48:53Z")

</div>

Hi -  
I’d like to be able to send a ‘cancel’ command to an async loop that runs in the background and fetches data.  
It’s not clear from the docs how I might do that - is this possible using channels?

---

<div class="post-metadata">

**Author:** ![ffevotte](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ffevotte/32/6587_2.png) [@ffevotte](https://discourse.julialang.org/u/ffevotte)\
**Post date:** [March 13, 2021, 12:55pm UTC](https://discourse.julialang.org/t/a-cancellable-async-loop/57068/2 "2021-03-13T12:55:30Z")

</div>

While channel-based solutions certainly exist, I’ve come to use [`schedule`](https://docs.julialang.org/en/v1/base/parallel/#Base.schedule) in combination with its `error` keyword-argument: it raises an exception in the task it wakes up, which I find easier to set up.

Here would be a minimal example:

```julia
julia> task = @async try
           while true
               println("Still running!")
               sleep(3)
           end
       catch
           println("Interrupted!")
       end
Still running!
Task (runnable) @0x00007f856dd324a0

julia> sleep(10); schedule(task, :STOP, error=true)
Still running!
Still running!
Still running!
Interrupted!
Task (runnable) @0x00007f856dd324a0

julia> task
Task (done) @0x00007f856dd324a0

```

---

<div class="post-metadata">

**Author:** ![danvenn](https://avatars.discourse-cdn.com/v4/letter/d/46a35a/32.png) [@danvenn](https://discourse.julialang.org/u/danvenn)\
**Post date:** [March 13, 2021, 1:43pm UTC](https://discourse.julialang.org/t/a-cancellable-async-loop/57068/3 "2021-03-13T13:43:58Z")

</div>

Thanks a lot, very helpful.
