diff --git a/src/util.jl b/src/util.jl index 5c77de2..4cbc1b6 100644 --- a/src/util.jl +++ b/src/util.jl @@ -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 + +