Skip to content

Instantly share code, notes, and snippets.

@bluegraybox
Created July 10, 2011 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluegraybox/1074932 to your computer and use it in GitHub Desktop.
Save bluegraybox/1074932 to your computer and use it in GitHub Desktop.
Erlang countdown timer which demonstrates code reloading
-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.
@bluegraybox
Copy link
Author

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