El proceso es muy simple, se envía un mensaje periodicamente al gen server con un mensaje concreto, y en la recepción de dicho mensaje realizamos la tareas necesarias, en este ejemplo mostramos un texto por pantalla.
Para realizar las llamadas periódicas al timer vamos a usar la función timer:send_interval/2.
send_interval(Time, Message) -> {ok, TRef} | {error, Reason}
Esta función se envía a sí misma el mensaje 'Message' repetidamente con un intervalo indicado en milisegundos (Time). Es decir, cada 'Time' milisegundos ejecuta 'Pid ! Message', donde el 'Pid' es el del proceso que lo ejecuta (Pid = self()).
Para leer el mensaje recibido en el gen_server utilizo el módulo handle_info/2.
A continuación se puede ver el código completo del gen server con un 'timer' periódico cada segundo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%%%------------------------------------------------------------------- | |
%%% @author Pablo Vieytes <mail@pablovieytes.com> | |
%%% @copyright (C) 2012, pablo | |
%%% @doc | |
%%% | |
%%% @end | |
%%% Created : 20 Jan 2012 by Pablo Vieytes <mail@pablovieytes.com> | |
%%%------------------------------------------------------------------- | |
-module(timer_gen_server). | |
-behaviour(gen_server). | |
%% API | |
-export([start_link/0]). | |
%% 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, {}). | |
%%%=================================================================== | |
%%% API | |
%%%=================================================================== | |
start_link() -> | |
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). | |
%%%=================================================================== | |
%%% gen_server callbacks | |
%%%=================================================================== | |
init([]) -> | |
Milisegs = 1 *1000, | |
timer:send_interval(Milisegs, periodic), | |
{ok, #state{}}. | |
handle_call(_Request, _From, State) -> | |
Reply = ok, | |
{reply, Reply, State}. | |
handle_cast(_Msg, State) -> | |
{noreply, State}. | |
handle_info(periodic, State) -> | |
io:format("timer testing~p", []), | |
{noreply, State}; | |
handle_info(_Info, State) -> | |
{noreply, State}. | |
terminate(_Reason, _State) -> | |
ok. | |
code_change(_OldVsn, State, _Extra) -> | |
{ok, State}. |
No hay comentarios:
Publicar un comentario