上一篇介紹了如何使用,這次看看具體實現
用github將項目拉到本地,看下項目具體的結構
可以看到項目是rebar3管理,遵循opt原則,集成travis ci 做集成測試。
項目啟動
- ecrn_app.erl 運行start/2
start(_StartType, _StartArgs) ->
case ecrn_sup:start_link() of
{ok, Pid} ->
setup(),
{ok, Pid};
Error ->
Error
end.
- ecrn_sup.erl 執行start_link/0
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
%% @private
init([]) ->
RestartStrategy = one_for_one,
MaxRestarts = 3,
MaxSecondsBetweenRestarts = 10,
SupFlags = {RestartStrategy,
MaxRestarts,
MaxSecondsBetweenRestarts},
ChildSup = {ecrn_cron_sup, {ecrn_cron_sup, start_link, []},
permanent, 1000, supervisor, [ecrn_cron_sup]},
RegistrationServer = {ecrn_reg_server, {ecrn_reg, start_link, []},
permanent, 1000, worker, [ecrn_reg]},
BroadcastServer = {ecrn_control, {ecrn_control, start_link, []},
permanent, 1000, worker, [ecrn_control]},
{ok, {SupFlags, [ChildSup, RegistrationServer, BroadcastServer]}}.
查看源碼可以看出ecrn_app:start_link() 分別啟動了三個子進程分別是
ecrn_cron_sup、ecrn_reg_server、ecrn_control
3.三個啟動模塊
- 我們先看ecrn_cron_sup啟動都做了些什么
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
init([]) ->
RestartStrategy = simple_one_for_one,
MaxRestarts = 1000,
MaxSecondsBetweenRestarts = 3600,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
Restart = transient,
Shutdown = 2000,
Type = worker,
AChild = {ecrn_agent, {ecrn_agent, start_link, []},
Restart, Shutdown, Type, [ecrn_agent]},
{ok, {SupFlags, [AChild]}}.
又去啟動了ecrn_agent,真是一層套一層,不過這也遵循了otp原則,這里可以看到啟動策略使用了simple_one_for_one,需要時創建子進程,初步考慮應當就是任務執行的最終模塊了
- 那接著我們再去看第二個啟動的ecrn_reg
-behaviour(gen_server).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
init([]) ->
{ok, #state{registered=dict:new()}}.
一個gen_server模塊,創建了一個進程字典,不過先不管他,看最后一個啟動的模塊
- ecrn_control
-behaviour(gen_server).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
init([]) ->
DateTime = erlang:localtime(),
{ok, #state{reference_datetime=DateTime,
datetime_at_reference=ecrn_util:epoch_seconds()}}.
也是一個gen_server 模塊,state里放了啟動時間,不過是兩種不同格式
3.三個進程啟動完了后在ecrn_app.erl 執行setup()
setup() ->
case application:get_env(erlcron, crontab) of
{ok, Crontab} ->
lists:foreach(fun(CronJob) ->
erlcron:cron(CronJob)
end, Crontab);
undefined ->
ok
end.
這里看到用了一個lists:foreach/2 循環執行在sys.config里配置的需要定時執行的任務。
具體如何做到循環執行的 就要看erlcron:cron/1是如何處理列表里job的了