How to stop a task started with `@schedule`


#1

Suppose I do something like the following:

i = 0
@schedule begin
  global i
  sleep(1)
  @show i
   i += 1
end

If I don’t grab the return value of @schedule (or for that matter even if I do), is there any sane way to stop the task from running? I say any sane way because I noticed that, at least for this example, I could effectively stop it by indirectly causing an exception to be raised:

julia> i = nothing
ERROR (unhandled task failure): MethodError: no method matching +(::Void, ::Int64)
Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...) at operators.jl:424
  +(::Complex{Bool}, ::Real) at complex.jl:247
  +(::Char, ::Integer) at char.jl:40
  ...
Stacktrace:
 [1] macro expansion at ./REPL[86]:5 [inlined]
 [2] (::##1770#1771)() at ./event.jl:73
julia> 

I did find #6283 which sounds like it would add what I’m asking about, but in the meantime is there a better way to achieve this?

Incidentally (and in case it suggests another approach), my actual use case for @schedule is for periodically emitting printouts to follow the status of an optimization being performed with NLopt.jl – AFAICT there’s no way to request it to provide such trace printouts and you have to build something into your objective function to accomplish this (yet – NLopt #16).


#2

Only way I know of is:

t = @schedule begin
    sleep(10)
end

@schedule Base.throwto(t,InterruptException())