Phoenix Controller Timer task

I want to create timer inside Phoenix Controller.

When timer expires, the conn will be redirected, if not, the query result will be returned.

Example User query, if query takes too long to process, the timer will kick in, and user will be redirected to notify that query took too long. i have tried Task.start and catch exits, but i haven’t figured it out.

  def index(conn, _params) do

    # set timer eg 2000
    # Process.send_after(self(), :test, 100) .. ?


    # heavy query:
    from user in User..



    IO.inspect(:done)

    # if timer expired before query was completed, 
    # redirect to ..
    # else

    conn
    |> render("done.html")
  end

A single process (and a controller action is handled in a single process) doesn’t execute code concurrently. So you either need to find ways to execute your heavy computation in chunks and check the timeout inbetween or you need multiple processes. The latter is the simpler option here:

task = Task.async(fn -> 
  # heavy computation
end)

case Task.yield(task, timeout) || Task.shutdown(task) do
  {:ok, result} -> # return result
  nil -> # handle timeout
end

Thanks. Works well :wink: