⏱️ Use these `:timer` helpers to remove magic ms numbers
Notes
Many functions in Elixir take milliseconds as an argument.
Take Process.sleep/1
as an example:
Process.sleep(300_000)
🤨 Uh… that’s okay, but unless you know how to read the Matrix, it’s hard to
know (at a glance) what 300_000
ms is in a more sensible unit.
Typically what I do is add clarity by creating a module attribute:
@five_minutes 1000 * 60 * 5
# in a function
Process.sleep(@five_minutes)
It’s easier to see that we’re passing data in milliseconds (the 1000
), and we
can see clearly that it’s 60
seconds times 5
(i.e. 5 minutes).
But there’s an even better way – and I only just learned about it recently.
Erlang’s :timer module has three functions to help us with this very issue:
iex> :timer.minutes(5)
# => 300000
iex> :timer.seconds(5)
# => 5000
iex> :timer.hours(5)
# => 18000000
That’ll make our code sooo clear!