Last active
July 2, 2018 10:53
-
-
Save kerryb/65069ec01752f8ff6272e217ae97d86d to your computer and use it in GitHub Desktop.
Supervised task, with timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Child do | |
def task(parent) do | |
Process.sleep(:timer.seconds(2)) | |
send(parent, :finished) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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