kaa.python

kaa.python

Task.await terminates GenServer because of timeout. How to fix?

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.

First 10 of 59 Posts Switch mode

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?

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
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
type1fool
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
akoutmos
@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're in Beta

About us Mission Statement