Created
July 10, 2011 20:22
-
-
Save bluegraybox/1074932 to your computer and use it in GitHub Desktop.
Erlang countdown timer which demonstrates code reloading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(countdown). | |
-export([init/0, reload/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) -> | |
register(ticker, spawn(?MODULE, tick, [Time])). | |
tick(Time) when Time >= 0 -> | |
io:format("Tick ~p~n", [Time]), | |
timer:sleep(999), | |
receive reload -> | |
?MODULE:tick(Time - 1) | |
after 1 -> tick(Time - 1) | |
end; | |
tick(_StartTime) -> | |
io:format("Boom.~n", []), | |
done. | |
reload() -> | |
ticker ! 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:
3> countdown_auto:init().
Tick 10
<0.219.0>
Tick 9
Tick 8
Tick 7
Tick 6
4> c(countdown_auto).
{ok,countdown_auto}
TICK!!! 5
TICK!!! 4
TICK!!! 3
TICK!!! 2
TICK!!! 1
TICK!!! 0
Boom.
5>
Whoa! The code updated as soon as it was loaded. Slick, but maybe a little too slick...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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().)