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’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
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
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
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
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
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
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Aludel - LLM Evaluation Workbench
Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
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
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #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