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.
When we run this program, the ticker should tick 3 times before we stop it.
In this Erlang version:
We define a module named
tickers
with amain/0
function.Instead of using channels, we use Erlang’s built-in message passing mechanism.
We spawn a new process that runs the
ticker_loop/0
function.We use
timer:send_interval/3
to send a ’tick’ message to our process every 500 milliseconds.The
ticker_loop/0
function uses areceive
block to handle incoming messages. It prints the current timestamp when it receives a ’tick’ message and exits when it receives a ‘stop’ message.In the main function, we sleep for 1600 milliseconds and then send a ‘stop’ message to our ticker process.
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.