首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ejabberd管理模块

ejabberd管理模块
EN

Stack Overflow用户
提问于 2009-12-24 02:06:58
回答 1查看 1.6K关注 0票数 2

我需要保持一个gen_mod进程运行,因为它每分钟循环一次,并进行一些清理。然而,每隔几天它就会崩溃一次,我将不得不手动重新启动它。

我可以使用一个在ejabberd_sup中实现管理程序的基本示例,这样它就可以继续运行。我正在努力理解使用gen_server的示例。

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2009-12-24 04:50:26

下面是一个结合了ejabberd的gen_mod和动态口令的gen_server的示例模块。解释内联在代码中。

代码语言:javascript
复制
-module(cleaner).

-behaviour(gen_server).
-behaviour(gen_mod).

%% gen_mod requires these exports
-export([start/2, stop/1]).

%% these are exports for gen_server
-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
         terminate/2, code_change/3]).

-define(INTERVAL, timer:minutes(1)).

-record(state, {}).

%% ejabberd calls this function when this module is loaded
%% basically it adds gen_server defined by this module to 
%% ejabberd main supervisor
start(Host, Opts) ->
    Proc = gen_mod:get_module_proc(Host, ?MODULE),
    ChildSpec = {Proc,
                 {?MODULE, start_link, [Host, Opts]},
                 permanent,
                 1000,
                 worker,
                 [?MODULE]},
    supervisor:start_child(ejabberd_sup, ChildSpec).

%% this is called by ejabberd when module is unloaded, so it
%% does the opposite of start/2 :)
stop(Host) ->
    Proc = gen_mod:get_module_proc(Host, ?MODULE),
    supervisor:terminate_child(ejabberd_sup, Proc),
    supervisor:delete_child(ejabberd_sup, Proc).

%% it will be called by supervisor when it is time to start
%% this gen_server under control of supervisor
start_link(_Host, _Opts) ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

%% it is an initialization function for gen_server
%% it starts a timer, which sends 'tick' message periodically to itself
init(_) ->
    timer:send_interval(?INTERVAL, self(), tick),
    {ok, #state{}}.

handle_call(_Request, _From, State) ->
    Reply = ok,
    {reply, Reply, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

%% this function is called whenever gen_server receives a 'tick' message
handle_info(tick, State) ->
    State2 = do_cleanup(State),
    {noreply, State2};

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


%% this function is called by handle_info/2 when tick message is received
%% so put all cleanup code here
do_cleanup(State) ->
    %% do all cleanup work here
    State.

This blog post很好地解释了gen_servers是如何工作的。当然,一定要重读gen_serversupervisor上的动态口令设计原则。

here描述了Ejabberd的模块开发

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1954402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档