hernancuy

hernancuy

Problem async Tasks from other module

Hello everybody, I’m creating an app service aggregator, I created some modules, my idea it’s one module create tasks and inside other module create the await and select only one task, after you select one task you will be get a mutex, but this is another history. So I’m using this modules, one is “App” and another is “Driver”, when you add the name of app, It goes to create some Task async, the names that I’m gonna use, are created by a random name creation line. Until now it’s working well, the issue comes, when I try to execute the async from another module, says that I’m sending two arguments, I modified the function to get two params but not works, how can I get this async from other modules ? =D thanks my friends

defmodule Tarea2 do

  defmodule App do

    @app Apps

    #### Start agent
    def start do
      Agent.start_link(fn -> %{} end,  name: @app)
    end

    #### Start tasks from app
    def task(app) do
      for x <- 0..4 do
        name = Enum.take_random(alphabet = Enum.to_list(?a..?e), 5)
        :timer.sleep(1000)
        name = Task.async(fn ->
              pid = self()
              ms = Enum.random(1..1000)
              info = "Codigo #{name} : Hernan Cuy, lugar x lugar y, 20000"
              Agent.update(@app, fn state -> Map.put(state, x, info) end)
              :timer.sleep(120000)
              IO.puts "#{inspect(pid)} finished in #{ms}ms"
              Agent.update(@app, fn state -> Map.delete(state, x) end)
          end)
      end
    end

    #### getNotifications
    def getNotifications do
      Agent.get(@app, fn state -> Map.values(state) end)
    end

    def taskReceiver(name) do
      Task.await(name)
    end

  end

  defmodule Central do

    @name __MODULE__

    #### Start the principal agent
    def start do
      Agent.start_link(fn -> {} end,  name: @name)
    end

    #### Add apps and start tasks
    def aggregator(app) do
      Agent.update(@name, fn state ->
        Tuple.append(state, app)
      end)

      Tarea2.App.task(app)
    end

    #### Get all apps
    def getApps do
      Agent.get(@name, fn state -> state end )
    end

  end

  defmodule Driver do
    @mut MutexRegion

    defstruct [name: "John", matricula: 28]

    def aggregator(app) do
      Tarea2.Central.start
      Tarea2.App.start
      Tarea2.Central.aggregator(app)
    end

    def taskReceiver do
      msg = Tarea2.App.getNotifications
    end

    def selectTask do
      taskSelected = String.trim(IO.gets("Ingrese codigo de solicitud a atender: "))
      Tarea2.App.taskReceiver(taskSelected)
      #Mutex.await(@defstruct, mutex2_id)
      #Process.sleep(1000)
      #Mutex.release(@defstruct, mutex1_id)
    end

  end

end

Here the error

iex(4)> Tarea2.Dirver.selectTask  

Ingrese codigo de solicitud a atender: bcdae
** (FunctionClauseError) no function clause matching in Task.await/2    

    The following arguments were given to Task.await/2:

        # 1
        "bcdae"

        # 2
        5000

    Attempted function clauses (showing 1 out of 1):

        def await(-%Task{ref: ref, owner: owner} = task-, timeout) when -timeout == :infinity- or is_integer(timeout) and timeout >= 0

    (elixir 1.13.2) lib/task.ex:794: Task.await/2

Marked As Solved

kartheek

kartheek

You are welcome @hernancuy .

I don’t think naming a task is possible and your code does not attempt it. It generated name and that name was overwritten by task returned by Task.async.

This is a naive implementation - i only addressed the name to task mapping part of it. Store name against corresponding task which was created in Agent state. Retrieve task for a given name and check if process is alive and await it if it is alive.

defmodule TestTask.App do

  @app Apps

  #### Start agent
  def start do
    Agent.start_link(fn -> %{tasks: %{}, data: %{}} end,  name: @app)
  end

  #### Start tasks from app
  def task(app) do
    for x <- 0..4 do
      name = Enum.take_random(alphabet = Enum.to_list(?a..?e), 5)
      task = 
        Task.async(fn -> 
          pid = self()
          ms = Enum.random(1..1000)
          info = "Codigo #{name} : Hernan Cuy, lugar x lugar y, 20000"
          Agent.update(@app, fn state -> 
            data = Map.put(state.data, x, info) 
            Map.put(state, :data, data)
          end)
          :timer.sleep(120000)
          Agent.update(@app, fn state -> 
            data = Map.delete(state.data, x) 
            tasks = Map.delete(state.tasks, name) 
            state
            |> Map.put( :data, data)
            |> Map.put( :tasks, tasks)
          end)
        end)
      Agent.update(@app, fn state -> 
        tasks = Map.put(state.tasks, name, task)
        Map.put(state, :tasks, tasks) 
      end)
      task
    end
  end

  def get() do
    Agent.get(@app, &(&1))
  end

  #### getNotifications
  def getNotifications do
    Agent.get(@app, fn state -> Map.values(state) end)
  end

  def taskReceiver(name) do
    task = Agent.get(@app, fn state -> Map.get(state.tasks, name) end)
    if task != nil and Process.alive?(task.pid) do
      Task.await(task)
    end
  end
end
iex(1)> alias TestTask.App
TestTask.App
iex(2)> App.start()
{:ok, #PID<0.472.0>}
iex(3)> App.get()
%{data: %{}, tasks: %{}}
iex(4)> App.task(nil)
iex(5)> App.get()
iex(6)> App.taskReceiver(<name>)

Also Liked

kartheek

kartheek

Task.await expects task to be passed - you are passing string. You may have to map name to a corresponding task.

hernancuy

hernancuy


 name = Enum.take_random(alphabet = Enum.to_list(?a..?e), 5)
        :timer.sleep(1000)
        name = Task.async(fn ->
              pid = self()

I don’t know if I’m doing wrong this name creation so, because the idea here is create a name random, and this name gonna be the name task. This is the string that I’m passing in the code that you see.

Do I need to pass the name like an atom ?

Thank you Kartheek :smiley:

hernancuy

hernancuy

Oh, I see!!!, thank you my friend, you give me the light and the idea to do that. Thank you !!!

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
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
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
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
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
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

We're in Beta

About us Mission Statement