Skip to content

Instantly share code, notes, and snippets.

@loxs
Created November 11, 2011 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loxs/1358140 to your computer and use it in GitHub Desktop.
Save loxs/1358140 to your computer and use it in GitHub Desktop.
-module(pinger).
-behaviour(gen_server).
%% API
-export([start_link/1, pong/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, {async_pid, worker_pid, worker_ref}).
start_link(AsyncPid) ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [AsyncPid], []).
init([AsyncPid]) ->
erlang:send_after(10000, self(), ping_someone),
{ok, #state{async_pid=AsyncPid}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(ping_someone, State) ->
{WorkerPid, WorkerRef} = async:spawn_call(pinger, pong, [], State#state.async_pid),
{noreply, State#state{worker_pid=WorkerPid, worker_ref=WorkerRef}};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
pong() ->
timer:sleep(10000).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment