kaa.python

kaa.python

My Genserver terminates after a little while, after sending a few http requests. I can’t understand the reason:

[error] GenServer MyGenServer terminating
** (stop) exited in: Task.await(%Task{owner: #PID<0.420.0>, pid: #PID<0.1054.0>, ref: #Reference<....>}, 5000)
    ** (EXIT) time out
    (elixir) lib/task.ex:416: Task.await/2
    (elixir) lib/enum.ex:966: Enum.flat_map_list/2
    (my_app123) lib/my_genserver.ex:260: MyApp.MyGenServer.do_work/1
    (my_app123) lib/my_genserver.ex:180: MyApp.MyGenServer.handle_info/2
    (stdlib) gen_server.erl:601: :gen_server.try_dispatch/4
    (stdlib) gen_server.erl:683: :gen_server.handle_msg/5
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Last message: :tick
State: [%{var1: "fdsafdsfd", var2: "43243242"}]

A chunk of the code:

  # it's called from handle_info

  def do_work(some_data) do
    Enum.map(some_data, fn(x) ->
      Task.async(fn ->
        case HTTPoison.post(.....) do
        # ...........

Is “Task.async” causing the timeout? But why? Yes, it can take more than 5 seconds to complete, but why does it cause an exception which then terminates GenServer? How to fix it?

About await:

If the timeout is exceeded, await will exit; however, the task will continue to run. When the calling process exits, its exit signal will terminate the task if it is not trapping exits.

Showing Posts 1 to 10

NobbZ

NobbZ

Task.await/1 calls exit/1 on timeout, so it will end your current process. If you do not wan’t that behaviour you will have to implement the receiving of the result and receiving of :DOWN messages on your own.

benperiton

benperiton

I’m still getting to grips with Tasks myself, but I think it’s because the Task is linked to the calling process, so if it throws an error and exits, then the calling process will also die. See Task — Elixir v1.20.2

You could use Task.start_link/1 if you don’t need the response, I’ve been using a Task.Supervisor for mine, so that if a Task dies, it doesn’t bring the genserver down.

Add a supervisor:

supervisor(Task.Supervisor, [[name: App.MyTaskSupervisor]])

Then can use it like:

def do_work(some_data) do
  Enum.map(some_data, fn(x) ->
    Task.Supervisor.async_nolink(App.MyTaskSupervisor, fn ->
      case HTTPoison.post(.....) do

Because I wnted to know if it was a timeout, I use yield

task = Task.Supervisor.async_nolink(
  App.MyTaskSupervisor,
  MyModule,
  :task_function,
  [args]
)

case Task.yield(task) || Task.shutdown(task) do
  {:ok, result} ->
    ack_message({:ok, %{channel: channel, tag: tag}})
  
  {:error, msg} ->
    ack_message({:error, %{error: msg, channel: channel, tag: tag, redelivered: redelivered}})

  {:exit, reason} ->
    ack_message({:error, %{error: reason, channel: channel, tag: tag, redelivered: redelivered}})

  nil ->
    ack_message({:error, %{error: "TIMEOUT", channel: channel, tag: tag, redelivered: redelivered}})
end
kaa.python

kaa.python OP

How and where?

Or maybe I could

  1. use try…catch inside Task.await
  2. or use Task.yield?
kaa.python

kaa.python OP

but I already have this in:

  def start(_type, _args) do
    import Supervisor.Spec

    children = [supervisor(MyWebApp.Repo, []), supervisor(MyWebApp.Endpoint, []),
                worker(MyWebApp.MyGenServer, [])]

    opts = [strategy: :one_for_one, name: MyWebApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
NobbZ

NobbZ

I’m not sure what you mean by using try/catch in Task.await/1, since you can’t alter Task.await/1. You can look at its implementation though to see how the different kind of messages look like, then you will know how to math them in handle_info/2. I’m not quite sure what will be the best way to time out a Task then, though…

If you mean you wan’t to wrap Task.await/1 with try/catch, this won’t work either. exit/1 does end the process. It does end the process. There is no try, nothing raised or thrown, only exit.

benperiton

benperiton

Again, I’m not sure this is the best way as I’m still learning myself, but something like:

Add supervisor(Task.Supervisor, [[name: MyWebApp.TaskSupervisor]]) to the app

def start(_type, _args) do
  import Supervisor.Spec

  children = [
    supervisor(MyWebApp.Repo, []),
    supervisor(MyWebApp.Endpoint, []),
    worker(MyWebApp.MyGenServer, []),
    supervisor(Task.Supervisor, [[name: MyWebApp.TaskSupervisor]]) # This is added
  ]

  opts = [strategy: :one_for_one, name: MyWebApp.Supervisor]
  Supervisor.start_link(children, opts)
end

Then inside MyWebApp.MyGenServer you could do:

def do_work(some_data) do
  Enum.map(some_data, fn(x) ->
    Task.Supervisor.async(MyWebApp.TaskSupervisor, fn -> # Use the Task.Supervisor here
      case HTTPoison.post(.....) do

The reason I switched to using Task.yield was because I wanted to be able to trap timeouts (it sends back nil) so that I could do something with it.

kaa.python

kaa.python OP

I mean this:

Task.async fn ->
  try do
    # http request
  catch
  end
end
kaa.python

kaa.python OP

How about Task.yield instead Task.async, will it work?

kaa.python

kaa.python OP

How will I know that it’s the “exit” or :DOWN sent exactly from that Task.await?

NobbZ

NobbZ

That of course would work, but you have to do it in every Task you spawn, also this will not do anything about a timeout in Task.await/1!


What do you wan’t to return in the case that there was no answer before having the yield timing out?

It won’t exit on raise though, but give you an :error-tuple which you could return straight.


By using a map to map your Task to your callers. roughly like this:

def handle_call(:foo, from, state) do
  task = Task.async(&do_stuff/0)
  state = Map.put(state, task.ref, from)
  {:noreturn, state}
end

How to pull of the correct value from the state is left as an exercise for the reader :wink: Also I have to admit that the code is untested since I currently have no access to a properly set up elixir environment.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
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
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews