samba6
I am trying to follow this blog Beyond Task.Async. So far I have got the following code working:
defmodule Aggregator do
@moduledoc """
Testing async tasks
"""
def new, do: 0
def aggregate(result), do: result
def aggregate(aggregator, result) do
Process.sleep(500)
aggregator + result
end
end
defmodule Calc do
@moduledoc """
Testing async tasks
"""
@spec run(Integer.t) :: Integer.t
def run(id) when id > 0 do
IO.puts "\n\n sleeping: #{id}"
Process.sleep(id)
IO.puts "\n\n waking from slumber: #{id}"
id
end
end
defmodule Async do
@moduledoc """
Testing async tasks
"""
def run(diff \\ 0, timeout \\ 900) do
1..10
|> Enum.map(fn _ -> Enum.random(1..1000) - diff end)
|> Enum.map(&Task.async(fn ->
try do
{:ok, Calc.run(&1)}
rescue _ ->
:error
end
end))
|> collect_result timeout
end
defp collect_result(tasks, timeout) do
ref = make_ref()
timer = Process.send_after(self(), {:timeout, ref}, timeout)
try do
collect_result(tasks, Aggregator.new, ref)
after
:erlang.cancel_timer(timer)
receive do
{:timeout, ^ref} ->
:ok
after 0 ->
:ok
end
end
end
defp collect_result([], aggregator, _), do: {:ok, Aggregator.aggregate(aggregator)}
defp collect_result(tasks, aggregator, ref) do
receive do
{:timeout, ^ref} ->
{:timeout, Aggregator.aggregate(aggregator)}
msg ->
case Task.find(tasks, msg) do
{{:ok, result}, task} ->
collect_result(
List.delete(tasks, task),
Aggregator.aggregate(aggregator, result),
ref
)
# if task errors, stop monitoring task and ignore its result
{:error, task} ->
collect_result(List.delete(tasks, task), aggregator, ref)
nil ->
collect_result(tasks, aggregator, ref)
end
end
end
end
So when I run: iex(295)> Async.run 700, I get {:ok, 489}
However, I read that Task.find was deprecated in favour of explicit message matching. So I refactored collect_result/3 to:
defp collect_result(tasks, aggregator, ref) do
receive do
{:timeout, ^ref} ->
{:timeout, Aggregator.aggregate(aggregator)}
{task, {:ok, result}} ->
collect_result(
List.delete(tasks, task),
Aggregator.aggregate(aggregator, result),
ref
)
# if task errors, stop monitoring task and ignore its result
{task, :error} ->
collect_result(List.delete(tasks, task), aggregator, ref)
end
end
Now Async.run times out no matter the value of diff. For examples, iex(306)> Async.run 700 returned {:timeout, 260}, which is ridiculous since Calc.run(260) was the only successful task.
I can’t seem to figure out how to refactor the code using explicit message matching and still get same behaviour as first iteration of the code. Any help from the community will be greatly appreciated.
Trending in Questions
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
Hello,
I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind.
However, when I launch mix phx.server, I get an error...
New
Hi everyone.
My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
Hello folks!
So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
I’m working on a small exercise involving update_in/3, and I came up with this solution:
data = %{
name: "Periodic Table",
category:...
New
How Can I Optimise Compile Time Dependencies
I have been building an elixir application for about 2 years now. Many modules and files ha...
New
Other Trending Topics
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
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
A little off-topic, but I feel like people here have a good head on their shoulders.
I used to be quite good at making software. Was luc...
New
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #ai
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #metaprogramming










Showing Posts 1 to 7- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
samba6
Ok, I got it working. I forgot that
Task.asyncreturns%Task{owner: owner, ref: ref, ...}so thatList.delete(tasks, task)did not delete thetasksincetasks = [%Task{}, %Task{}, ...], buttaskis a reference. So I got thetaskselement corresponding totaskusing the code below:And so
collect_result/3becomes:Now I the timeout message is sent only when a task runs for longer than the timeout. But I’m thinking may be there is a better way of achieving same result. Any help in this regard will be appreciated.
peerreynders
Might as well use a Map
What particular avenue of improvement did you have in mind?
At this point I’m wondering whether
TaskentirelyThe more I’m exposed to
Taskthe more I’m predisposed to shoving it over into the corner withAgentas a nice curiosity which ultimately isn’t all that useful.OvermindDL1
It has a few limited uses, I do not think the use with GenServer is such a use though and GenServer should just be used.
I’ve
legitused Task only a couple of times total, and I could have easily done them another way (which really might have been shorter code too).samba6
Thanks @peerreynders. Your corrections worked. I asked if there was a better way because I happened to look at
Task.findafter I had writtenget_matched_task/2and they looked similar. SinceTask.findwas deprecated, I thought a function which does almost the same thing had to be defective.I really like the cleanups you introduced. It solved a headache I was having where I’d get
{:DOWN, _, _, _, _}messages and couldn’t figure out where they were coming from. I tried usingobserver.startto see if I could catch them, but I guess since those processes had exited before I turned toobserver, I wouldn’t find them.I am truly grateful. Thanks
peerreynders
So here is an approach where you essentially handle the spawned processes by yourself.
.
In the end though you shouldn’t spin off processes just because you can. Make sure there is a “good enough reason” for the process to exist. Have a really good, long look at The Erlangelist: To spawn, or not to spawn?
Edit: Added some more
IO.putsto reveal more information to help explain behaviour that may seem strange on first blush.samba6
Thanks a lot. That
Genservercode looks so nice - something I will be adding to my tool set. And thanks for the advice about spawning processes. I was trying to wrap my head around how concurrency works in elixir, and your advice was timely because I can see myself overdoing it.Do have a great day!
samba6
Thanks @peerreynders, I learnt a lot