Skip to content

Instantly share code, notes, and snippets.

@FilippoVajana
Created February 5, 2020 11:47
Show Gist options
  • Save FilippoVajana/0d3ac1f8d5a6439168fcb74988091aa7 to your computer and use it in GitHub Desktop.
Save FilippoVajana/0d3ac1f8d5a6439168fcb74988091aa7 to your computer and use it in GitHub Desktop.
Julia @async function with timeout
struct CBCSolverResult
# job_result::Symbol
solver_status::String
solver_result
end
CBC_SOLVE_RESULT = CBCSolverResult("Failed", Nothing)
long_running_job(do_times) =
begin
# call CBC solver
i = 0
while i < do_times
println("Job iter: ", i)
i += 1
sleep(1)
end
global CBC_SOLVE_RESULT = CBCSolverResult("Terminated", i)
throw(InterruptException())
end
run_timed_job(do_times, timeout) =
begin
# clear global variable
global CBC_SOLVE_RESULT = CBCSolverResult("Failed", Nothing)
# async background job
bg_task = @async long_running_job(do_times)
@info "Started job: " bg_task
# check function
check_func(timer) =
begin
if istaskstarted(bg_task) && !istaskdone(bg_task)
@warn "Job blocked"
global CBC_SOLVE_RESULT = CBCSolverResult("Timeout", nothing)
Base.throwto(bg_task, InterruptException())
end
end
# when the timer is triggered we call check_func().
t = Timer(check_func, timeout, interval = 0)
wait(t)
sleep(1)
close(t)
return bg_task
end
function run_solver(do_times = 5, timeout = 10)
try
job_result = @sync run_timed_job(do_times, timeout)
catch ex
if isa(ex, InterruptException)
if CBC_SOLVE_RESULT.solver_status == "Terminated"
@info "Job completed with:
\tStatus: $(CBC_SOLVE_RESULT.solver_status)
\tResult: $(CBC_SOLVE_RESULT.solver_result)"
elseif CBC_SOLVE_RESULT.solver_status == "Timeout"
@error "Job $(CBC_SOLVE_RESULT.solver_status)"
end
else
@error "Job $(CBC_SOLVE_RESULT.solver_status)"
@error ex
end
end
end
# terminate
run_solver(5, 10)
# timeout
run_solver(10, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment