- 论坛徽章:
- 27
|
本帖最后由 shijiang1130 于 2014-07-01 21:44 编辑
- ,再改一版
- -module(my_ping).
- -behaviour(gen_event).
- -compile(export_all).
- t_ping()->
- gen_event:start({local,monitor}),
- gen_event:add_handler(monitor,my_ping,"warning.txt"),
- P = open_port({spawn,"c:/windows/system32/PING.exe -t www.chinaunix.net"},[binary,exit_status]),
- loop(P).
- loop(P)->
- receive
- {P,{data,Data}} ->
- case re:run(Data,<<"(\\d+)ms\s">>,[{capture,[1],list}]) of
- {match,[Res]} -> io:format("~n~p",[Res]),
- Num=erlang:list_to_integer(Res),
- average(Num),
- alert(Num);
- _ -> ok
- end,
- loop(P)
- end.
- alert(Num)->
- case Num > 10 of
- true ->
- %io:format("!!!! warning"),
- gen_event:notify(monitor,[erlang:integer_to_list(Num)]);
- false -> ok
- end.
- average(Num)->
- case get(count) of
- undefined->
- put(count,1),
- put(total,Num);
- _ ->
- exception
- end,
- C=get(count),
- T=get(total),
- P=T/C,
- io:format(" => average is: ~p~n",[P]),
- put(count,C+1),
- put(total,T+Num).
- %%% gen_event part
- init(File)->
- {ok,Fd} = file:open(File,write),
- {ok,Fd}.
- handle_event(Event,Fd)->
- {{Year,Month,Day},{Hour,Min,Second}}=calendar:local_time(),
- Time_stamp = lists:concat([Year,"-",Month,"-",Day," ",Hour,":",Min,":",Second]),
- io:format(Fd,"[Warning] ~p ~p~n",[Time_stamp,Event]),
- {ok,Fd}.
- terminate(_Args,Fd)->
- file:close(Fd).
复制代码 |
|