How to close a remote Timer?

I want to run mutliple procedures in parallel on a server in fixed time ntervals. The idea was to ,e.g., simply use “@spawnat :any” together with “Timer”, however, I cannot find a way to stop the Timer once its started. Does anyone know how to stop this?

# if started on a worker, how can I stop this? close(?)
unstoppable = fetch(@spawnat(:any, Timer((x)->println("Hello"), 0; interval = 10)))

The other way around, using a “Timer” to trigger "@spawnat :any"s, it can be stopped using close, but I would prefer to have the first approach running, as I have persistent data between each run.

1 Like

e.g. write a callback function that closes the timer when it receives a stop message:

using Distributed
nprocs() == 1 && addprocs(2);

@everywhere struct Stop end

rch = [RemoteChannel(()->Channel(1), 1) for _ in 1:nprocs()]

@everywhere function doit(rch) # callback function
    (timer) -> begin
        ch = rch[myid()]
        stop = isready(ch) && take!(ch) isa Stop
        stop ? close(timer) : println("Hello")
    end
end

then for example

julia> @spawnat 2 Timer(doit(rch), 0; interval=5);

julia>       From worker 2:     Hello
      From worker 2:    Hello
      From worker 2:    Hello
      From worker 2:    Hello
julia> put!(rch[2], Stop());

julia>
2 Likes

Exactly what I was looking for, thanks a lot!

I’m actually a big fan of Julia’s message passing facilities. Many concurrency problems can be solved with it.

If you want to tell an asynchronous process something, consider how to pass a message to it. :wink:

1 Like