0
-define(INTERVAL, 1000).

init([]) ->
    Timer = erlang:send_after(?INTERVAL, self(), tick),
    {ok, Timer}.

handle_info(tick, OldTimer) ->
    erlang:cancel_timer(OldTimer),
    io:format("Tick ~w~n", [OldTimer]),
    Timer = erlang:send_after(?INTERVAL, self(), tick).
    {noreplay, Timer}.

start_clock() ->
    {_, Timer} = init([]),
    spawn(clock, handle_info, [tick, Timer]).

My codes is as above, but the output is not what I want. How can I integrate init() and handle_info() into the main function(start_clock)?

Wyatt
  • 1,357
  • 5
  • 17
  • 26
  • 3
    What /is/ your output? What kind of output are you expecting? – Arnon Mar 09 '15 at 16:14
  • Is that all the code there is? In my answer I assumed those were callbacks in a gen_server. – Stratus3D Mar 09 '15 at 18:33
  • Relevant: [What's the best way to do something periodically in Erlang?](https://stackoverflow.com/questions/769466/whats-the-best-way-to-do-something-periodically-in-erlang?rq=1) – Flux May 19 '19 at 10:31

2 Answers2

2

In the timer module, the function apply_interval(Time, Module, Function, Arguments) executes Module:Function(Arguments) every interval of Time. It takes care of spawning a process, returns a reference to allow a cancellation later.

You also can have a look at send_interval(Time, Pid, Message) in the same library.

You can also implement a simple loop like:

loop(Args,Tick) when is_integer(Tick), Tick >= 0 ->
    receive
        stop -> stopped
    after 
        Tick ->
            do_something(Args),
            {NewArgs,NewTick} = new_args(Args,Tick), 
            loop(NewArgs,NewTick)
    end.

it is not a realtime timer, but the function new_args(Args,Tick) can help to correct the deviation due to process scheduling.

Pascal
  • 13,977
  • 2
  • 24
  • 32
0

I think you need something like this:

start_timer() ->
    gen_server:start_link({local, clock}, ?MODULE, [], []).
P_A
  • 1,804
  • 1
  • 19
  • 33