Search code examples
elixirelixir-mix

Mix task spawning a process does nothing


I created a mix task which spawns a process. It uses Flow, reads from a stream and writes into a file defined in a consumer.

At the end of the day it just spawn some processes.

If I run it through iex it works fine as long as I leave the shell running.

But if I launch it from the command line as a mix task nothing happens, how do you leave the process opened?

  use Flow

  def run([stream]) do
    specs = [{{ProdCon,[]},[]}]
    consumer = [{{Consumer,[]},[]}]

    stream
    |> Flow.from_enumerable()
    |> Flow.through_specs(specs)
    |> Flow.into_specs(consumer)
  end

Solution

  • Spawn a Task doing the job and wait until it finishes with Task.yield/2:

    use Flow
    
    def run([stream]) do
      task = Task.async(fn ->
    
        specs = [{{ProdCon,[]},[]}]
        consumer = [{{Consumer,[]},[]}]
    
        stream
        |> Flow.from_enumerable()
        |> Flow.through_specs(specs)
        |> Flow.into_specs(consumer)
    
      end)
    
      case Task.yield(task, 3_600) do # wait 1 hour
        {:ok, result} -> result
        nil -> IO.puts("Failed to get a result :(")
      end
    end