你可以试试这个代码:进程worker1
每秒关闭一次,进程worker2
每两秒关闭一次。您只需要加载两个梁,并super:start_link(). super:main().
在 erl shell 中运行。
这是超级用户:
-module(super).
-behaviour(supervisor).
%% API
-export([start_link/0]).
-export([stop/0]).
-export([main/]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
init([]) ->
RestartStrategy = simple_one_for_one,
MaxRestarts = 1000,
MaxSecondsBetweenRestarts = 3600,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
Restart = permanent,
Shutdown = 2000,
Type = worker,
AChild = {worker, {worker, start_link, []},
Restart, Shutdown, Type, [worker]},
{ok, {SupFlags, [AChild]}}.
main() ->
add_worker(worker1, 1000),
add_worker(worker2, 2000).
add_worker(WorkerName, Time) when is_atom(WorkerName)->
supervisor:start_child(?SERVER, [WorkerName, Time]).
stop() ->
exit(whereis(?SERVER), shutdown).
这是 gen_server:
-module(worker).
-behaviour(gen_server).
%% API
-export([start_link/2]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {}).
start_link(WorkerName, Time) ->
io:format("server: ~p start!~n", [WorkerName]),
gen_server:start_link({local, WorkerName}, ?MODULE, [WorkerName, Time], []).
init([WorkerName, Time]) ->
erlang:send_after(Time, self(), {WorkerName, timeout_shutdown}),
{ok, #state{}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({WorkerName, timeout_shutdown}, State) ->
io:format("server: ~p timeout_shutdown!~n", [WorkerName]),
{stop, normal, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.