123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- -module(myapp_events).
- -behaviour(gen_server).
- -export([start_link/0]).
- -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
- -export([add_task/4, delete_task/2]).
- -define(IS_STRING(S), (is_list(S) andalso S /= [] andalso is_integer(hd(S)))).
- add_task(Task_Id, Proc_Id, Type, Time)
- when ?IS_STRING(Task_Id), is_integer(Proc_Id), ((Type =:= static) orelse (Type =:= dynamic)), is_integer(Time) ->
- Time2 = case Type of
- dynamic ->
- erlang:system_time(second) + Time; % Timestamp_Now + Time
- _ ->
- % static
- Time
- end,
- gen_server:cast(?MODULE, {add_task, {Task_Id, Proc_Id, Time2}}),
- ok.
- delete_task(Task_Id, Proc_Id)
- when ?IS_STRING(Task_Id), is_integer(Proc_Id) ->
- gen_server:cast(?MODULE, {delete_task, {Task_Id, Proc_Id}}),
- ok.
- start_link() ->
- gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
- init([]) ->
- erlang:send_after(100, self(), check_time_process),
- State = [],
- {ok, State}.
- handle_call(_Req, _From, State) ->
- {reply, not_handled, State}.
- handle_cast({add_task, {Task_Id, Proc_Id, _Time}=V}, State) ->
- State2 = lists:filter(fun({Task_Id0, Proc_Id0, _Time0}) ->
- if Task_Id =:= Task_Id0 andalso Proc_Id =:= Proc_Id0 ->
- io:format("update: ~p ~p~n", [Task_Id0, Proc_Id0]),
- false;
- true -> true
- end
- end, State),
- {noreply, [V|State2]};
- handle_cast({delete_task, {Task_Id, Proc_Id}}, State) ->
- State2 = lists:filter(fun({Task_Id0, Proc_Id0, _Time}) ->
- if Task_Id =:= Task_Id0 andalso Proc_Id =:= Proc_Id0 ->
- io:format("deleted: ~p ~p~n", [Task_Id0, Proc_Id0]),
- false;
- true -> true
- end
- end, State),
- {noreply, State2};
- handle_cast(_Req, State) ->
- {noreply, State}.
- handle_info(check_time_process, []) ->
- erlang:send_after(1000, self(), check_time_process),
- {noreply, []};
- handle_info(check_time_process, State) ->
- Timestamp_Now = erlang:system_time(second),
- State2 = lists:filtermap(fun({Task_Id0, Proc_Id0, Time0}=V) ->
- if Time0 =< Timestamp_Now ->
- % send_to_rabbitmq({call_timer, Proc_Id0, Task_Id0}),
- io:format("tick: ~p ~p~n", [Task_Id0, Proc_Id0]),
- false;
- true -> {true, V}
- end
- end, State),
-
- erlang:send_after(1000, self(), check_time_process),
- {noreply, State2};
- handle_info(_Request, State) ->
- {noreply, State}.
- terminate(_Reason, _State) ->
- ok.
- code_change(_OldVsn, State, _Extra) ->
- {ok, State}.
|