Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Timer(f, ...) tasks match the stickiness of the parent task. Add spawn kwarg. #56745

Merged
merged 10 commits into from
Jan 6, 2025
11 changes: 9 additions & 2 deletions base/asyncevent.jl
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ end

# timer with repeated callback
"""
Timer(callback::Function, delay; interval = 0)
Timer(callback::Function, delay; interval = 0, spawn::Bool=true)
IanButterworth marked this conversation as resolved.
Show resolved Hide resolved

Create a timer that runs the function `callback` at each timer expiration.

Expand All @@ -285,6 +285,12 @@ callback is only run once. The function `callback` is called with a single argum
itself. Stop a timer by calling `close`. The `callback` may still be run one final time, if the timer
has already expired.

If `spawn` is `false`, the created task will be marked as sticky, meaning that it will not be allowed
to move thread, which will also prevent the task that created the timer from moving thread.

!!! compat "Julia 1.12"
The `spawn` argument was introduced in Julia 1.12.

# Examples

Here the first number is printed after a delay of two seconds, then the following numbers are
Expand All @@ -304,7 +310,7 @@ julia> begin
3
```
"""
function Timer(cb::Function, timeout; kwargs...)
function Timer(cb::Function, timeout; spawn::Bool=true, kwargs...)
IanButterworth marked this conversation as resolved.
Show resolved Hide resolved
timer = Timer(timeout; kwargs...)
t = @task begin
unpreserve_handle(timer)
Expand All @@ -319,6 +325,7 @@ function Timer(cb::Function, timeout; kwargs...)
isopen(timer) || return
end
end
t.sticky = !spawn
# here we are mimicking parts of _trywait, in coordination with task `t`
preserve_handle(timer)
@lock timer.cond begin
Expand Down
Loading