stratacast

stratacast

Best way to name permanent tasks?

I’m trying to name a supervised, permanent task so I can find it easier. What’s the best way to go about this? I tried out this right here:

https://hexdocs.pm/elixir/1.10.3/Task.html#module-supervised-tasks

However, when I run Process.whereis(MyApplication.MyTask) instead of getting a PID back, I get nil. This is an ongoing looping task. From MyApplication.Application I also tried moving the starting of the Task via a different Supervisor call like so:

Supervisor.start_link([
  {MyTask, arg}
], strategy: :one_for_one, id: :"MyApplication.MyTask")

And that didn’t seem to work either. I don’t know what exactly the :id would do, but I thought it was worth trying to pass that along.

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Tasks are really not the right kind of thing to have running for a long time, you should use a genserver instead.

However to your specific question, id is not the value used to set the name, you need a name option, but I’m not even sure if tasks take a name option.

NobbZ

NobbZ

Indeed, Task.start_link/3 does not allow for something like the :name option.

https://hexdocs.pm/elixir/v1.10/%20/Task.html

ityonemo

ityonemo

Process.register/2 should work. But yeah. At the point where you have a stateless datastructure receiving messages inside a task, it’s time to use gen_statem. If you prefer a genserver like interface and enforced state graph on top of gen_statem, I wrote StateServer library for this purpose.

Otoh, if you’re doing this for fun and exploration of otp I highly encourage it!!

ityonemo

ityonemo

use Task, restart: :permanent

seems not right, IMO. I don’t think statefulness/not statefulness is the right way to think about whether or not you should use a GenServer vs. a Task. There are times where I have GenServer equivalents with state nil.

I would say a GenServer is supposed to be a service, and a Task is supposed to be an action. If you speak a romance language, GenServers are imperfective and Tasks are perfective. Tasks IIRC are a creation of Elixir to give OTP a sane default way to supervise simple things with strictly internal control flow, but as soon as you’re doing message passing to interface with a task, you’re in GenServer territory.

If you are having a Task that is permanent, it must somehow be responding to a message (probably a receive block?). Although that might work for now, I would suggest changing that over to a GenServer call. If for no other reason than the caller will know if the somehow the GenServer is unavailable. Even if all your call does is reply :ok and performs a {:continue, info} to actually do its thing. That will let the GenServer manage your message queue instead of doing it manually. This is good because you’ll get solid error warnings (the calling GenServer will crash), and you’ll also get backpressure management.

If your needed throughput for your service starts go get really high, you’re going to want to do process pools, and buliding out a process pool from a GenServer is a well-trodden, battle-tested, and relatively formulaic process; doing so with a Task I suspect could be challenging.

jswanner

jswanner

As stated, :gen_statem has a concept of event timeouts, where the timeout will be automatically cancelled if an event is received before the timeout expires. You create an event timeout by returning an “event timeout” action from a callback

{state, data, [:timer.seconds(5)]}
# or
{state, data, [{:timeout, :timer.seconds(5), value_to_include_in_callback}]}

Alternatively, if you want control over when the timeout is cancelled, you can use a generic timeout. As long as you keep returning the same generic timeout name from callbacks, then the timeout will keep being reset (or you can explicitly cancel it), otherwise the timeout expires and the process will receive a message about it.

{state, data, [{{:timeout, :my_name}, :timer.seconds(5), value_to_include}]}

GenServer also has builtin timeout support that can be used to detect inactivity:

def handle_info(:timeout, state) do
  dbg("5 seconds of inactivity have elapsed")
  {:noreply, state}
end

def handle_info(_, state) do
  {:noreply, state, :timer.seconds(5)}
end

And, if you want to be in control over when the timeout is cancelled, you can do so with Process.send_after/4 and Process.cancel_timer/2:

def handle_info(:timeout, state) do
  dbg("5 seconds of inactivity have elapsed")
  {:noreply, state}
end

def handle_info(_, state) do
  if state.timer, do: Process.cancel_timer(state.timer)
  state = put_in(state.timer, Process.send_after(self(), :timeout, :timer.seconds(5)))
  {:noreply, state}
end

Where Next?

Popular in Questions Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New

We're in Beta

About us Mission Statement