This commit is contained in:
narawat lamaiin
2024-08-20 23:03:40 +07:00
parent a5dc2c1122
commit 4ac9a7ee12
2 changed files with 52 additions and 18 deletions

View File

@@ -123,7 +123,40 @@ main()
error("test done")
function run_with_timeout(f, args...; timeout=5)
result = Ref{Any}()
task = Threads.@spawn try
result[] = f(args...)
catch e
println("Task interrupted: ", e)
end
Timer(timeout) do _
if !istaskdone(task)
schedule(task, InterruptException())
println("Task did not complete in time. Aborting.")
else
println("Task completed within the timeout.")
end
end
return result[]
end
# Example function that takes arguments and returns a value
function example_function(x, y)
sleep(10) # Simulate a long-running task
return x + y
end
# Example usage
result = run_with_timeout(example_function, 3, 4; timeout=5)
println("Result: ", result)