Skip to content

Instantly share code, notes, and snippets.

@caingougou
Created September 24, 2014 10:11
Show Gist options
  • Save caingougou/62749634129c12dfac66 to your computer and use it in GitHub Desktop.
Save caingougou/62749634129c12dfac66 to your computer and use it in GitHub Desktop.
Erlang gen_server and supervisor template
-module(test).
-export([start_link/0]).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, {}, []).
%% @private
init({}) ->
{ok, undefined}.
% here the function to handle the test_function call with params
handle_call({test_function, Params}, _From, State) ->
Reply = [],
{reply, Reply, State}.
%% @private
handle_call(_Request, _From, State) ->
{reply, {error, unknown_call}, State}.
%% @private
handle_cast(_Msg, State) ->
{noreply, State}.
%% @private
handle_info(_Info, State) ->
{noreply, State}.
%% @private
terminate(_Reason, _State) ->
ok.
%% @private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
test_function(Params) ->
gen_server:call(?MODULE, {test_function, Params}).
-module(test_sup).
-export([start_link/0]).
-behaviour(supervisor).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, {}).
%% @private
init({}) ->
Worker = {test, {test, start_link, []}, permanent, 5000, worker, [test]},
% {Tag, {Mod, Fun, ArgList}, Restart , Shutdown, Type, [Mod] },
% Restart : permanent | transient | temporary
% permanent : always restart
% transient : restart only if terminates with a non-normal exit value
%
% Shutdown :
% if takes longer than this value to terminate, it will be killed.
Workers = [Worker],
RestartStrategy = {one_for_one, 5, 10},
{ok, {RestartStrategy, Workers}}.
@nikita-fuchs
Copy link

thanks a ton for this !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment