你可以試試這個代碼:進程worker1
每秒關機一次,進程worker2
每隔兩秒關機一次。 您只需加載兩個光束,然後在erl外殼中運行super:start_link(). super:main().
。
這是supervosor:
-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}.
謝謝你的回覆。但是,在處理消息時,我遇到了終止進程的問題。所以問題是當進程死了時它仍然處於主管狀態,並且不可能用相同的名稱啓動進程,因爲主管說{error,already_present},有沒有解決方法?再次感謝! –