Joe talks about spawning processes and receiving messages with timeouts, and then goes about building a timer using these concepts. This version makes it a bit more dynamic and self-changing according to messages you send the timer once you create it.
It also shows how you can use recursion to build a periodic timer..
Code:
Explanation:
-module(xtimer).
-export([make/2]).
make(Period, Message) -> spawn(fun () -> start(Period, Message) end).
start(Period, Message) ->
receive
NewMessage when is_list(NewMessage) -> start(Period, NewMessage);
NewPeriod when is_number(NewPeriod) -> start(NewPeriod, Message)
after Period ->
io:format("~p~n", [Message]),
start(Period, Message)
end.
1. The first 2 lines are self-explanatory
2. The make function is what we call from the shell and it spawns a timer which prints Message every Period milliseconds. Make also returns the timer's Pid which we use to control it.
3. We then send messages to our timer using its Pid to change its behaviour (Message/Period).
everytime you need to change the timer properties, No need to stop and restart, just send it a message! try doing that in any other language :-)
Test run..
Eshell V5.5.5 (abort with ^G)
2> Timer = xtimer:make(2000, "Joel loves erlang!").
<0.38.0>
"Joel loves erlang!"
"Joel loves erlang!"
"Joel loves erlang!"
"Joel loves erlang!"
"Joel loves erlang!"
3> Timer ! "Timer message changes....".
"Timer message changes...."
"Timer message changes...."
"Timer message changes...."
"Timer message changes...."
"Timer message changes...."
4> Timer ! 3000. % Timer is now slower...
3000
"Timer message changes...."
"Timer message changes...."
"Timer message changes...."
5> q().