david234
Task Supervisor with max_restart and max_seconds
I am working on a code that will ping an external API every 15 minutes, to retrieve the response and store it in the database.
def get_forecast(city) do
app_id = My.api_key()
query_params = URI.encode_query(%{"q" => city, "APPID" => app_id})
url =
"https://api.weather.org/data/2.5/forecast?" <> query_params
case HTTPoison.get(url) do
{:ok, %HTTPoison.Response{status_code: 200} = response} ->
{:ok, Jason.decode!(response.body)}
{:ok, %HTTPoison.Response{status_code: status_code}} ->
{:error, {:status, status_code}}
{:error, reason} ->
{:error, reason}
end
end
I am running this inside a Task, and that Task is running inside a Genserver.
In application.ex
use Application
def start(_type, _args) do
children = [
# Starts a worker by calling: FsiIntegration.Worker.start_link(arg)
# {FsiIntegration.Worker, arg}
{Task.Supervisor, name: Integration.TaskSupervisor, restart: :transient, max_restarts: 3, max_seconds: 4000}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Integration.Supervisor]
Supervisor.start_link(children, opts)
end
In genserver file
defmodule Integration.FsiServer do
use GenServer
@timeout 15000
#Public API
def start_task do
GenServer.start_link(__MODULE__, %{ref: nil}, name: __MODULE__)
end
def execute_task(pid) do
GenServer.call(pid, {:execute, @timeout})
end
#Callbacks API
def init(state) do
{:ok, state}
end
# In this case the task is already running, so we just return :ok.
def handle_call({:execute, _task_timeout}, _from, %{ref: ref} = state) when is_reference(ref) do
{:reply, :ok, state}
end
# The task is not running yet, so let's start it.
def handle_call({:execute, task_timeout}, _from, %{ref: nil} = state) do
IO.inspect state
task =
Task.Supervisor.start_child(Integration.TaskSupervisor, fn ->**
{:ok, _} = IntegrationGet.get_forecast("city")**
end)
{:reply, :ok, %{state | ref: task.ref}}
end
# The task completed successfully
def handle_info({ref, answer}, %{ref: ref} = state) do
Process.demonitor(ref, [:flush])
{:noreply, %{state | ref: nil}}
end
# The task failed
def handle_info({:DOWN, ref, :process, _pid, _reason}, %{ref: ref} = state) do
{:noreply, %{state | ref: nil}}
end
end
My questions are :
I know I have to improve on the below code. Can you guys me insight on how to make this better
use Application
def start(_type, _args) do
children = [
# Starts a worker by calling: FsiIntegration.Worker.start_link(arg)
# {FsiIntegration.Worker, arg}
{Task.Supervisor, name: Integration.TaskSupervisor, restart: :transient, max_restarts: 3, max_seconds: 4000}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Integration.Supervisor]
Supervisor.start_link(children, opts)
end
def handle_call({:execute, task_timeout}, _from, %{ref: nil} = state) do
IO.inspect state
task =
Task.Supervisor.start_child(Integration.TaskSupervisor, fn ->
{:ok, _} = IntegrationGet.get_forecast("city")
end)
{:reply, :ok, %{state | ref: task.ref}}
end
-
The time interval between restarts I have set max_seconds to 5 seconds. But the restart happens immediately.
-
Is Task.Supervisor.start_child is good for making an external API request. Just it will make a single API request in this case. Or I have to go for async_nolink or async under Task module
My use case is request an external API and store the response in the DB.
Trending in Discussions
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
New
@chrismccord : I just saw the Extract AGENTS.md from Phoenix.new into phx.new generator commit to the phoenix project.
My initial shotgu...
New
I was working on an Ecto migration and I needed a timestamp. So, for the nth time, I looked up the different data types for timestamps, a...
New
Just a general thread to post chat/news/info relating to AI/ML stuff that may be relevant for Nx now or in the future. Got anything to sh...
New
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog
It says that Fly is going all-in on sprites, which is a worry ...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New
We want to introduce a new native datatype to Erlang: native records. Although replacing all tuple records with native records is not our...
New
Latest Phoenix Threads
Chat & Discussions>Discussions
Latest on Elixir Forum
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #hex
- #performance










First 4 of 4 Posts
kwando
The
max_restartsandmax_secondsoptions only states how many (max_restarts) restarts of a child in a time period of time (max_seconds) the supervisor should tolerate before crashing.You can read about
max_secondshere: Supervisor — Elixir v1.20.2.andreaseriksson
I like option 3 here:
But with the part of handling a failure, I would put in a sleep
LostKobrakai
sleepwill block the process from handling anything else in the meantime. It’s usually better to usesent_intervalto receive another message at a later time to trigger the restart, but staying responsive to other messages.andreaseriksson
True, 100% agree. Was in ruby land for a moment