Correct way to wait for a Timer callback to execute

Use case in case it matters is to have non-flaky unit tests without having to over-abstract things (which is why I’d prefer to not have some boolean iscallbackdone inside the callback).

function testtimer()
    ss = ""
    tt = Timer(1) do t 
        ss *= "aa"
    end
    wait(tt)
    ss *= "bb"
    sleep(1.1)
    return ss
end

julia> testtimer() # Want "aabb"
"bbaa"

Putting a yield() or similar between timer start and wait(tt) makes the function produce the desired output, but I doubt it will be robust enough to pass on free CI.

This works, but I want to have a reference to the timer so I can stop (close) it:


function testtask()
    ss = ""
    tt = @async begin
            wait(Timer(1) do t 
                ss *= "aa"
            end) 
        end
    wait(tt)
    ss *= "bb"
    sleep(1.1)
    return ss
end

julia> testtask()
"aabb"

Not sure what your ultimate goal is here. But I think you could do something like:

function testtimer()
    cond=Condition()
    c = 0
    ss = ""
    tt = Timer(1) do t 
        ss *= "aa"
        c += 1
        notify(cond)
    end
    while c < 2
        wait(cond)
        if c == 1
            ss *= "bb"
        end
    end
    return ss
end

Thanks, although that looks a bit more messy than what I had hoped for.

I ended up doing something like this instead:


function starttimer(delay, stuff...)
return Timer(delay) do _
     timerexpiry(stuff...)
end
function timerexpiry(stuff...)
  #stuff with stuff
end

And then just test timerexpiry in testcases.