Skip to content

Instantly share code, notes, and snippets.

@kerryb
Last active July 2, 2018 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerryb/65069ec01752f8ff6272e217ae97d86d to your computer and use it in GitHub Desktop.
Save kerryb/65069ec01752f8ff6272e217ae97d86d to your computer and use it in GitHub Desktop.
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