Today I Learned

hashrocket A Hashrocket project

`sleep` is just `receive after`

While using sleep in your production application might not be for the best, it's useful in situations where you're simulating process behaviour in a test or when you're trying to diagnose race conditions.

The Elixir docs say this:

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.

There's nothing special about sleep though. The implementation for both :timer.sleep and Process.sleep is equivalent. In Elixir syntax, it's:

receive after: (timeout -> :ok)

So, it's waiting for a message, but doesn't provide any patterns that would successfully be matched. It relies on the after of receive to initiate the timeout and then it returns :ok.

If you're building out some production code that requires waiting for a certain amount of time, it might be useful to just use the receive after code so that if later you decide that the waiting can be interrupted you can quickly provide a pattern that would match the interrupt like:

timeout = 1000

receive do
  :interrupt -> 
    :ok_move_on_now
  
  after
    timeout -> :ok_we_waited
end
See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.