devie
devie

Reputation: 332

Start Elixir Task after Completion of another Task

Please Using the Task Module, what's the best approach in starting Task Y after Task X has completed or after x Seconds of Task X Starting?

Upvotes: 0

Views: 357

Answers (1)

Steve Pallen
Steve Pallen

Reputation: 4507

Based on your requirement to start Y either when X finishes or after 5 seconds, you should use a message to signal task Y and give Y a timeout. This should do the trick:

defmodule Schedule do
  def run do
    IO.puts "running it..."
    spawn &task1/0
  end

  def task1 do
    pid = spawn &task2/0

    # do your work here
    IO.puts "working on task 1"
    :timer.sleep 6_000
    send pid, :start
    IO.puts " task 1 done"
  end

  def task2 do
    receive do
      :start -> :ok
      after 
        5_000 ->  :ok
    end
    # do your work here
    IO.puts "working on task 2"
  end
end

You could use Tasks too, but not really needed for a simple case.

Upvotes: 1

Related Questions