Hi, I’m Erika Rowland (a.k.a. erikareads). Hi, I’m Erika. I’m an Ops-shaped Software Engineer, Toolmaker, and Resilience Engineering fan. I like Elixir and Gleam, Reading, and Design. She/Her. Constellation Webring Published on

Legible Timeouts with Erlang’s timer

By convention, timeouts in Erlang (and Elixir) are set in units of milliseconds. However, this isn’t type checked by either language, so you end up with magic integers for timeouts throughout a codebase.

While both Erlang and Elixir support underscores in numbers for readability: 5_000, you’re still expected to know that timeouts are in milliseconds.

Enter timer

Erlang’s timer provides legible helper functions for expressing timeouts:

timer:seconds/1

timer:minutes/1

timer:hours/1

Each takes an integer and converts it from the stated time to milliseconds.

timer also provides timer:hms/3 for hours, minutes, and seconds, returning their sum in milliseconds.

Using :timer in Elixir

Elixir supports seamless integration of Erlang standard library functions, though the syntax is a bit different:

:timer.seconds(5)

So you can replaceI’ve considered using an opaque type to force the use of legible functions, but that would involve wrapping every function in Erlang and Elixir that uses a timeout, which isn’t practical.:

Process.sleep(5000)

with:

Process.sleep(:timer.seconds(5))

Takeaway

Next time you need to set a timeout in Erlang or Elixir, consider using timer to embed your design decisions and communicate without magic numbers.Thanks to Zach for pointing me to timer!


Constellation Webring