samba6
Saša Jurić's "Beyond Task.Async" blog
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 in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
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
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated!
To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead.
Sta...
New
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app?
Looking for hints regarding:
Addi...
New
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
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
Hello,
I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
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
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
@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
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 7 of 7 Posts
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