Skip to content

Instantly share code, notes, and snippets.

@yatender-oktalk
Last active February 8, 2021 04:39
Show Gist options
  • Save yatender-oktalk/b3b6686df81a095074f656fdc8a5dcaf to your computer and use it in GitHub Desktop.
Save yatender-oktalk/b3b6686df81a095074f656fdc8a5dcaf to your computer and use it in GitHub Desktop.
Async tasks in a process failsafe
defmodule Sender.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
# Starts a worker by calling: Sender.Worker.start_link(arg)
# {Sender.Worker, arg}
{Task.Supervisor, name: Sender.EmailTaskSupervisor}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Sender.Supervisor]
Supervisor.start_link(children, opts)
end
end
defmodule Sender do
@moduledoc """
Documentation for `Sender`.
"""
@doc """
Hello world.
## Examples
iex> Sender.hello()
:world
"""
def hello do
:world
end
def send_email("konnichiwa@world.com" = email),
do: raise("Oops, couldn't send email to #{email}!")
def send_email(email) do
Process.sleep(3000)
IO.inspect("Email to #{email} sent")
{:ok, "email sent"}
end
def notify_all(emails) do
Sender.EmailTaskSupervisor
|> Task.Supervisor.async_stream_nolink(emails, &send_email/1)
|> Enum.to_list()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment