A cancellable async loop?

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?

While channel-based solutions certainly exist, I’ve come to use 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> 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
7 Likes

Thanks a lot, very helpful.