myapp_events.erl 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. -module(myapp_events).
  2. -behaviour(gen_server).
  3. -export([start_link/0]).
  4. -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
  5. -export([add_task/4, delete_task/2]).
  6. -define(IS_STRING(S), (is_list(S) andalso S /= [] andalso is_integer(hd(S)))).
  7. add_task(Task_Id, Proc_Id, Type, Time)
  8. when ?IS_STRING(Task_Id), is_integer(Proc_Id), ((Type =:= static) orelse (Type =:= dynamic)), is_integer(Time) ->
  9. Time2 = case Type of
  10. dynamic ->
  11. erlang:system_time(second) + Time; % Timestamp_Now + Time
  12. _ ->
  13. % static
  14. Time
  15. end,
  16. gen_server:cast(?MODULE, {add_task, {Task_Id, Proc_Id, Time2}}),
  17. ok.
  18. delete_task(Task_Id, Proc_Id)
  19. when ?IS_STRING(Task_Id), is_integer(Proc_Id) ->
  20. gen_server:cast(?MODULE, {delete_task, {Task_Id, Proc_Id}}),
  21. ok.
  22. start_link() ->
  23. gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
  24. init([]) ->
  25. erlang:send_after(100, self(), check_time_process),
  26. State = [],
  27. {ok, State}.
  28. handle_call(_Req, _From, State) ->
  29. {reply, not_handled, State}.
  30. handle_cast({add_task, {Task_Id, Proc_Id, _Time}=V}, State) ->
  31. State2 = lists:filter(fun({Task_Id0, Proc_Id0, _Time0}) ->
  32. if Task_Id =:= Task_Id0 andalso Proc_Id =:= Proc_Id0 ->
  33. io:format("update: ~p ~p~n", [Task_Id0, Proc_Id0]),
  34. false;
  35. true -> true
  36. end
  37. end, State),
  38. {noreply, [V|State2]};
  39. handle_cast({delete_task, {Task_Id, Proc_Id}}, State) ->
  40. State2 = lists:filter(fun({Task_Id0, Proc_Id0, _Time}) ->
  41. if Task_Id =:= Task_Id0 andalso Proc_Id =:= Proc_Id0 ->
  42. io:format("deleted: ~p ~p~n", [Task_Id0, Proc_Id0]),
  43. false;
  44. true -> true
  45. end
  46. end, State),
  47. {noreply, State2};
  48. handle_cast(_Req, State) ->
  49. {noreply, State}.
  50. handle_info(check_time_process, []) ->
  51. erlang:send_after(1000, self(), check_time_process),
  52. {noreply, []};
  53. handle_info(check_time_process, State) ->
  54. Timestamp_Now = erlang:system_time(second),
  55. State2 = lists:filtermap(fun({Task_Id0, Proc_Id0, Time0}=V) ->
  56. if Time0 =< Timestamp_Now ->
  57. % send_to_rabbitmq({call_timer, Proc_Id0, Task_Id0}),
  58. io:format("tick: ~p ~p~n", [Task_Id0, Proc_Id0]),
  59. false;
  60. true -> {true, V}
  61. end
  62. end, State),
  63. erlang:send_after(1000, self(), check_time_process),
  64. {noreply, State2};
  65. handle_info(_Request, State) ->
  66. {noreply, State}.
  67. terminate(_Reason, _State) ->
  68. ok.
  69. code_change(_OldVsn, State, _Extra) ->
  70. {ok, State}.