add timeout function

This commit is contained in:
2024-09-20 14:21:05 +07:00
parent c8684dea31
commit de3eead3a4

View File

@@ -1,7 +1,7 @@
module util
export timedifference, showstracktrace, findHighestIndexKey, uuid4snakecase, replaceDictKeys,
findMatchingDictKey, textToDict, randstring, randstrings
findMatchingDictKey, textToDict, randstring, randstrings, timeout
using JSON3, DataStructures, Distributions, Random, Dates, UUIDs, MQTTClient
@@ -369,6 +369,49 @@ end
""" Execute a function with timer.
# Arguments
- `f::Function`
a function to run
- `timeoutwindow::Integer``
timeout in seconds
# Keyword Argument
- `fargs`
arguments for the function
# Return
- task result otherwise timeout message
# Example
```jldoctest
julia> function testfunc(x)
sleep(x)
return "task done"
end
julia> result = timeout(testfunc, 10; fargs=20)
"task timed out"
julia> result = timeout(testfunc, 20; fargs=10)
"task done"
```
# Signature
"""
function timeout(f::Function, timeoutwindow::Integer; fargs=nothing, timeoutmsg="task timed out")
tsk = @task f(fargs)
schedule(tsk)
Timer(timeoutwindow) do timer
istaskdone(tsk) || Base.throwto(tsk, InterruptException())
end
try
fetch(tsk)
catch _;
timeoutmsg
end
end