Skip to content

Instantly share code, notes, and snippets.

@kerryb
Last active Jul 2, 2018
Embed
What would you like to do?
Supervised task, with timeout
defmodule Child do
def task(parent) do
Process.sleep(:timer.seconds(2))
send(parent, :finished)
end
end
defmodule MyTaskSupervisor do
def run(timeout) do
Process.flag(:trap_exit, true)
{:ok, child_pid} = Task.start_link(Child, :task, [self()])
timer = Process.send_after(self(), :timeout, timeout)
wait(child_pid, timer)
end
defp wait(child_pid, timer) do
receive do
{:EXIT, ^child_pid, reason} ->
IO.puts("Child exited with reason #{inspect(reason)}")
Process.cancel_timer(timer)
# Handle task timeout here
:timeout ->
IO.puts "Timeout: killing child"
Process.exit(child_pid, :kill)
wait(child_pid, timer)
:finished ->
IO.puts("Child has finished")
Process.cancel_timer(timer)
# Handle normal response here
msg ->
IO.inspect(msg)
wait(child_pid, timer)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment