[erlang-questions] Erlang timer program - feedback please

Sean Payne <>
Fri Oct 3 20:52:09 CEST 2008


I am hoping someone with more Erlang experience than me could give me some
feedback on the timer code below.

I am using erlang:start_timer and tail recursion with a paused state and a
running state to create a little simulation
* world:init(). inits the sim
* world:run(). starts the updates (right now updates just print out
"updating")
* world:pause(). pauses the updates
* world:destroy(). shuts it down

So my questions are:
1) Is there a better way (timer wise) to do this. I suspect that the way I
am using the timer that my update_now will not be called at the right
frequency because of the delay between when the event fires and when the
next event is scheduled.

2) Is there a better way Erlang wise to do something like this.  I am new to
Erlang, so I am curious if this is the approach that someone with more
experience would take.  Is this how you would write this?????

3) Are there any bugs or leaks?  ie am I using Tail recursion correctly?
(every time I pause or unpause the program, am I going deeper into the
stack?)

Thanks,

Sean

=========================================
-module(world).

%% External interfaces
%% world:init sets up the world (into the paused state)
%% world:run starts the timers and updates every UPDATE_INTERVAL
%% world:stop pauses the world
%% world:destroy destroys the world
-export([init/0]).
-export([run/0]).
-export([stop/0]).
-export([destroy/0]).

%% internal functions but must be exported to receive events from
erlang:start_timer
-export([handle_events_while_stopped/0]).
-export([handle_events_while_running/0]).

-define(UPDATE_INTERVAL,1000).

handle_events_while_stopped() ->
    receive
        finished->
            io:format("world is finished~n", []);
        run->
            io:format("world is running~n", []),
            erlang:start_timer(?UPDATE_INTERVAL, self(), update_now),
            handle_events_while_running()
    end.

handle_events_while_running() ->
    receive
        finished->
            io:format("world is finished~n", []);
        stop->
            io:format("world is stopping~n", []),
            handle_events_while_stopped();
        {timeout, _ , update_now} ->
            io:format("updating~n", []),
            erlang:start_timer(?UPDATE_INTERVAL, self(), update_now),
            handle_events_while_running()
    end.


init() ->
    register(world, spawn(world, handle_events_while_stopped,[])).

run()->
    world ! run.

stop()->
    world ! stop.

destroy()->
    world ! finished.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081003/e6edc5e5/attachment.html>


More information about the erlang-questions mailing list