Process.sleep
sleep
, go back to Process module for more information.
Specs
sleep(timeout()) :: :ok
Sleeps the current process for the given timeout
.
timeout
is either the number of milliseconds to sleep as an
integer or the atom :infinity
. When :infinity
is given,
the current process will sleep forever, and not
consume or reply to messages.
Use this function with extreme care. For almost all situations
where you would use sleep/1
in Elixir, there is likely a
more correct, faster and precise way of achieving the same with
message passing.
For example, if you are waiting for a process to perform some action, it is better to communicate the progress of such action with messages.
In other words, do not:
Task.start_link(fn ->
do_something()
...
end)
# Wait until work is done
Process.sleep(2000)
But do:
parent = self()
Task.start_link(fn ->
do_something()
send(parent, :work_is_done)
...
end)
receive do
:work_is_done -> :ok
after
# Optional timeout
30_000 -> :timeout
end
For cases like the one above, Task.async/1
and Task.await/2
are
preferred.
Similarly, if you are waiting for a process to terminate, monitor that process instead of sleeping. Do not:
Task.start_link(fn ->
...
end)
# Wait until task terminates
Process.sleep(2000)
Instead do:
{:ok, pid} =
Task.start_link(fn ->
...
end)
ref = Process.monitor(pid)
receive do
{:DOWN, ^ref, _, _, _} -> :task_is_down
after
# Optional timeout
30_000 -> :timeout
end