From de3eead3a4f48d12815b8e92c865dd20b355bb4a Mon Sep 17 00:00:00 2001 From: tonaerospace Date: Fri, 20 Sep 2024 14:21:05 +0700 Subject: [PATCH] add timeout function --- src/util.jl | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) 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 + +