|-export([tick/1]). % so we can spawn this properly.|
|%% spawn a countdown process with a default start time of 10 seconds.|
|init() -> init(10).|
|register(ticker, spawn(?MODULE, tick, [Time])).|
|tick(Time) when Time >= 0 ->|
|io:format("Tick ~p~n", [Time]),|
|receive reload ->|
|?MODULE:tick(Time - 1)|
|after 1 -> tick(Time - 1)|
|ticker ! reload.|
Start up an Erlang shell, compile this module, and run init():
Edit the source and change the message on line 11 to "TICK!!!". Until it's compiled, the tick() process that init() spawns will still be running the old version of the code. Fire it up.
Now you compile the new code, but the tick process is already running with the old code. It's when you call reload() that tick() calls the new version of the code.
So, on the fly code updates in a handful of lines. Not quite magic, but pretty easy, and it leaves you in control of when the code reloads. Nice.
(In case you're wondering, the "true" and "reload" that you see in the output are the return values from init() and reload().)
Actually, if you want to see the "no brakes" version, it's:
-module(countdown_auto). -export([init/0]). -export([tick/1]). % so we can spawn this properly. %% spawn a countdown process with a default start time of 10 seconds. init() -> init(10). init(Time) -> spawn(?MODULE, tick, [Time]). tick(Time) when Time >= 0 -> io:format("Tick ~p~n", [Time]), timer:sleep(1000), ?MODULE:tick(Time - 1); tick(_Time) -> io:format("Boom.~n", ).
In this case, the output looks like:
Whoa! The code updated as soon as it was loaded. Slick, but maybe a little too slick...