多进程工作者的全局定时器 替代单进程工作模式的erlangtimer
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

54 行
1.0 KiB

  1. -module(gTimer).
  2. -include("gTimer.hrl").
  3. -export([
  4. start/0
  5. , stop/0
  6. , startWork/1
  7. , setTimer/2
  8. , getTimer/1
  9. , delTimer/1
  10. ]).
  11. timerName(Idx) ->
  12. binary_to_atom(<<"$gtWSork_", (integer_to_binary(Idx))/binary>>).
  13. startWork(Cnt) when Cnt > 0 ->
  14. case ?gTimerCfg:getV(?workCnt) of
  15. 0 ->
  16. NameList = [{Idx, timerName(Idx)} || Idx <- lists:seq(1, Cnt)],
  17. [supervisor:start_child(gTimer_sup, [WorkName]) || {_Idx, WorkName} <- NameList],
  18. CfgList = [{?workCnt, Cnt} | NameList],
  19. gtKvsToBeam:load(?gTimerCfg, CfgList),
  20. ok1;
  21. _Cnt ->
  22. {error, started}
  23. end.
  24. start() ->
  25. application:ensure_all_started(gTimer).
  26. stop() ->
  27. gtKvsToBeam:load(?gTimerCfg, [{?workCnt, 0}]),
  28. application:stop(gTimer).
  29. setTimer(Time, Msg) ->
  30. Cnt = ?gTimerCfg:getV(?workCnt),
  31. Idx = erlang:phash2(self(), Cnt) + 1,
  32. erlang:start_timer(Time, ?gTimerCfg:getV(Idx), Msg).
  33. getTimer(TimerRef) ->
  34. erlang:read_timer(TimerRef).
  35. delTimer(TimerRef) ->
  36. erlang:cancel_timer(TimerRef).