在gen_server中实现定时功能(方法二)
2011-07-04 01:18
399 查看
转载请注明,来自:http://blog.csdn.net/skyman_2001
在gen_server的init、handle_call、handle_cast 或handle_info函数里的返回元祖的第3个元素是个整数,代表
代码如下:-module(otp_test).
-behaviour(gen_server).
-export([start_link/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
init([]) ->
%% Note we must set trap_exit = true if we
%% want terminate/2 to be called when the application
%% is stopped
process_flag(trap_exit, true),
io:format("~p starting~n",[?MODULE]),
{ok, state, 5000}. % 5000是timeout间隔
handle_call(_Msg, _From, State) ->
{noreply, State, 5000}.
handle_cast(_Msg, State) ->
{noreply, State, 5000}.
%% handle timeout message
handle_info(timeout, State) ->
io:format("tick~n",[]),
{noreply, State, 5000}.
terminate(_Reason, _State) ->
io:format("~p stopping~n",[?MODULE]),
ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
运行:otp_test:start_link().
结果:otp_test starting
{ok,<0.59.0>}
tick
tick
tick
tick
tick
...
在gen_server的init、handle_call、handle_cast 或handle_info函数里的返回元祖的第3个元素是个整数,代表
timeout的间隔(单位为ms),则时间到时会发送timeout消息给进程,该消息通过handle_info()来处理。
代码如下:-module(otp_test).
-behaviour(gen_server).
-export([start_link/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
init([]) ->
%% Note we must set trap_exit = true if we
%% want terminate/2 to be called when the application
%% is stopped
process_flag(trap_exit, true),
io:format("~p starting~n",[?MODULE]),
{ok, state, 5000}. % 5000是timeout间隔
handle_call(_Msg, _From, State) ->
{noreply, State, 5000}.
handle_cast(_Msg, State) ->
{noreply, State, 5000}.
%% handle timeout message
handle_info(timeout, State) ->
io:format("tick~n",[]),
{noreply, State, 5000}.
terminate(_Reason, _State) ->
io:format("~p stopping~n",[?MODULE]),
ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
运行:otp_test:start_link().
结果:otp_test starting
{ok,<0.59.0>}
tick
tick
tick
tick
tick
...
相关文章推荐
- 在gen_server中实现定时功能(方法一)
- ASP.NET MVC计划任务实现方法(定时执行某个功能)
- quartz实现定时功能实例详解(servlet定时器配置方法)
- 使用Java实现简单的server/client回显功能的方法介绍
- 用超时来实现gen_server的定时
- win-server下定时备份oracle数据库实现方法
- 使用Java实现简单的server/client回显功能的方法介绍
- js获取前端时间方法,并且实现定时刷新页面的功能
- quartz实现定时功能实例详解(servlet定时器配置方法)
- go实现定时功能两种方法
- 使用Java实现简单的server/client回显功能的方法介绍
- quartz实现定时功能实例详解(servlet定时器配置方法)
- JS中如何实现sleep功能 js定时执行方法
- Cisco 设备 实现 IOS DHCP Server的功能
- 【学以致用】android功能实现9---Launcher之AS中,在Launcher源码中增加google负一屏的实现方法
- Java实现定时任务的三种方法
- C#基于纯数学方法递归实现货币数字转换中文功能详解
- 99、Android中定时执行任务的3种实现方法
- CentOS下使用rsync实现定时复制功能