How to make sure a task interrupts when it takes too long

If you want to interrupt a task, it needs yield() statements somewhere. sleep already has them, so it’s interruptible.

For example, this can’t be interrupted:

function foo()
       i = 0
       while true
           i += 1
       end
end

@async foo()

But this can:

function foo()
       i = 0
       while true
           i += 1
           yield()
       end
end
@async foo()

Per the documentation, yield will “Switch to the scheduler to allow another scheduled task to run. A task that calls this function is still runnable, and will be restarted immediately if there are no other runnable tasks.”

1 Like