Timers in Erlang

In Erlang, we can use timers to execute code at a specific point in the future. Let’s explore how to use timers in Erlang.

-module(timers).
-export([main/0]).

main() ->
    % Timers represent a single event in the future. You
    % tell the timer how long you want to wait, and it
    % will send a message when that time has elapsed.
    % This timer will wait 2 seconds.
    {ok, Timer1} = timer:send_after(2000, timer1),
    
    % We wait to receive the message from the timer
    receive
        timer1 ->
            io:format("Timer 1 fired~n")
    end,

    % If you just wanted to wait, you could have used
    % timer:sleep/1. One reason a timer may be useful is
    % that you can cancel the timer before it fires.
    % Here's an example of that.
    {ok, Timer2} = timer:send_after(1000, timer2),
    
    % Spawn a process to wait for Timer2
    spawn(fun() ->
        receive
            timer2 ->
                io:format("Timer 2 fired~n")
        after 2000 ->
            ok
        end
    end),

    % Cancel Timer2
    case timer:cancel(Timer2) of
        {ok, cancel} ->
            io:format("Timer 2 stopped~n");
        {error, _Reason} ->
            io:format("Timer 2 already fired or doesn't exist~n")
    end,

    % Give Timer2 enough time to fire, if it ever
    % was going to, to show it is in fact stopped.
    timer:sleep(2000).

To run this program, save it as timers.erl and use the Erlang shell:

$ erl
1> c(timers).
{ok,timers}
2> timers:main().
Timer 1 fired
Timer 2 stopped
ok

The first timer will fire approximately 2 seconds after we start the program, but the second should be stopped before it has a chance to fire.

In this Erlang version:

  1. We use timer:send_after/2 to create timers that send messages after a specified time.
  2. We use receive to wait for timer messages.
  3. We spawn a separate process to handle Timer2, simulating the goroutine in the original example.
  4. We use timer:cancel/1 to stop a timer before it fires.
  5. We use timer:sleep/1 for simple delays.

Erlang’s built-in timer module provides these functionalities, making it easy to work with timed events in your programs.