Skip to content

Instantly share code, notes, and snippets.

@vinoski
Created April 6, 2016 19:00
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 vinoski/d869123ebce87f8631cb1bcc016aeedd to your computer and use it in GitHub Desktop.
Save vinoski/d869123ebce87f8631cb1bcc016aeedd to your computer and use it in GitHub Desktop.
example gen_server
-module(gs).
-behaviour(gen_server).
-export([start/0, stop/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {count}).
start() ->
gen_server:start({local, ?MODULE}, ?MODULE, [], [{debug,[trace]}]).
stop() ->
gen_server:cast(?MODULE, stop).
init([]) ->
gen_server:cast(self(), step1),
{ok, #state{count=0}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(step1, #state{count=3}=State) ->
{stop,normal,State};
handle_cast(step1, State) ->
gen_server:cast(self(), step2),
{noreply, State};
handle_cast(step2, State) ->
gen_server:cast(self(), step3),
{noreply, State};
handle_cast(step3, State) ->
gen_server:cast(self(), step4),
{noreply, State};
handle_cast(step4, State) ->
gen_server:cast(self(), step5),
{noreply, State};
handle_cast(step5, #state{count=Count}=State) ->
gen_server:cast(self(), step1),
{noreply, State#state{count=Count+1}};
handle_cast(stop, State) ->
{stop,normal,State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment