Tickers in Erlang

Tickers are used when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.

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

main() ->
    % Tickers use a similar mechanism to timers: a process that sends messages
    % at regular intervals. Here we'll use the receive construct to await the
    % messages as they arrive every 500ms.
    Pid = spawn(fun() -> ticker_loop() end),
    timer:send_interval(500, Pid, tick),

    % We'll stop our ticker after 1600ms.
    timer:sleep(1600),
    Pid ! stop,
    io:format("Ticker stopped~n").

ticker_loop() ->
    receive
        tick ->
            io:format("Tick at ~p~n", [erlang:timestamp()]),
            ticker_loop();
        stop ->
            ok
    end.

When we run this program, the ticker should tick 3 times before we stop it.

$ erl -noshell -s tickers main -s init stop
Tick at {1655,908544,123456}
Tick at {1655,909044,234567}
Tick at {1655,909544,345678}
Ticker stopped

In this Erlang version:

  1. We define a module named tickers with a main/0 function.

  2. Instead of using channels, we use Erlang’s built-in message passing mechanism.

  3. We spawn a new process that runs the ticker_loop/0 function.

  4. We use timer:send_interval/3 to send a ’tick’ message to our process every 500 milliseconds.

  5. The ticker_loop/0 function uses a receive block to handle incoming messages. It prints the current timestamp when it receives a ’tick’ message and exits when it receives a ‘stop’ message.

  6. In the main function, we sleep for 1600 milliseconds and then send a ‘stop’ message to our ticker process.

  7. Finally, we print “Ticker stopped” to indicate that the ticker has been stopped.

This Erlang code demonstrates how to create a periodic ticker using Erlang’s concurrency primitives and message passing.