<div dir="ltr">I am hoping someone with more Erlang experience than me could give me some feedback on the timer code below.<br><br><div class="gmail_quote"><div dir="ltr">I am using erlang:start_timer and tail recursion with a paused state and a running state to create a little simulation<br>
* world:init(). inits the sim<br>* world:run(). starts the updates (right now updates just print out "updating")<br>* world:pause(). pauses the updates<br>* world:destroy(). shuts it down<br><br>So my questions are:<br>
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.<br>
<br>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?????<br><br>
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?)<br><br>Thanks,<br><br>Sean<br><br>=========================================<br>
-module(world).<br><br>%% External interfaces <br>%% world:init sets up the world (into the paused state)<br>
%% world:run starts the timers and updates every UPDATE_INTERVAL<br>%% world:stop pauses the world<br>%% world:destroy destroys the world<br>-export([init/0]).<br>-export([run/0]).<br>-export([stop/0]).<br>-export([destroy/0]).<br>
<br>%% internal functions but must be exported to receive events from erlang:start_timer<br>-export([handle_events_while_stopped/0]).<br>-export([handle_events_while_running/0]).<br><br>-define(UPDATE_INTERVAL,1000).<br>
<br>
handle_events_while_stopped() -><br> receive<br> finished-><br> io:format("world is finished~n", []);<br> run-><br> io:format("world is running~n", []),<br>
erlang:start_timer(?UPDATE_INTERVAL, self(), update_now),<br> handle_events_while_running()<br> end.<br><br>handle_events_while_running() -><br> receive<br> finished-><br> io:format("world is finished~n", []);<br>
stop-><br> io:format("world is stopping~n", []),<br> handle_events_while_stopped();<br> {timeout, _ , update_now} -><br> io:format("updating~n", []),<br>
erlang:start_timer(?UPDATE_INTERVAL, self(), update_now),<br> handle_events_while_running()<br> end.<br><br><br>init() -><br> register(world, spawn(world, handle_events_while_stopped,[])).<br>
<br>run()-><br> world ! run.<br><br>stop()-><br> world ! stop.<br> <br>destroy()-><br> world ! finished.<br></div>
</div><br></div>